import { ageOn, parseFormDate, today } from "../../shared/dates.js";
import { parsePhone } from "../../shared/phone.js";

export interface Issue { field: string; code: string; message: string; severity: "error" | "warning" }
export interface EnumLookup { (domain: string, raw: string): string | undefined }
/** The single list of registration columns: template, import, form and checks all come from here. */
export const COLUMNS: { key: string; required?: boolean; max?: number }[] = [
  { key: "first_name", required: true }, { key: "father_name", required: true }, { key: "grandfather_name", required: true }, { key: "sex", required: true }, { key: "age", required: true }, { key: "date_of_birth", required: true }, { key: "phone", required: true },
  { key: "region", required: true }, { key: "woreda", required: true, max: 120 }, { key: "education", required: true }, { key: "employment", required: true }, { key: "class_code", required: true }, { key: "roster_status", required: true }, { key: "form_date", required: true },
  { key: "external_beneficiary_id", max: 100 }, { key: "phone_alternative" }, { key: "email", max: 190 }, { key: "kebele", max: 120 }, { key: "sub_city", max: 120 }, { key: "emergency_contact_name", max: 190 }, { key: "emergency_contact_phone" },
  { key: "previously_participated" }, { key: "prior_training_type", max: 190 }, { key: "prior_completed" }, { key: "prior_year_completed" }, { key: "income_sufficient" }, { key: "skill_usage" }, { key: "plan" }, { key: "plan_other", max: 190 },
  { key: "disability" }, { key: "disability_other", max: 190 }, { key: "is_pwd" }, { key: "is_idp" }, { key: "is_returnee" }, { key: "is_low_income" }, { key: "inclusion_none" }, { key: "inclusion_prefer_not_to_say" },
  { key: "consent_accuracy", required: true }, { key: "consent_followup" }, { key: "consent_contact_verify", required: true }, { key: "consent_image_use" },
];
const ALIASES: Record<string, string> = { date_of_form_completion: "form_date", date_of_birth_et_calendar: "date_of_birth", dob: "date_of_birth", age_years: "age", phone_primary: "phone", highest_education: "education", employment_status: "employment", roster_role: "roster_status", batch_code: "class_code", class: "class_code", post_training_employment_plan_type: "plan", post_training_employment_plan_other_text: "plan_other", disability_type: "disability", disability_other_text: "disability_other", disability_flag: "is_pwd", idp_flag: "is_idp", returnee_flag: "is_returnee", low_income_flag: "is_low_income", inclusion_none_of_above: "inclusion_none", consent_followup_surveys: "consent_followup", emergency_phone: "emergency_contact_phone", emergency_name: "emergency_contact_name", phone_alt: "phone_alternative" };
const squash = (s: string) => s.replace(/_/g, "");
const BY_KEY = new Map([...COLUMNS.map((c) => [squash(c.key), c.key] as const), ...Object.entries(ALIASES).map(([a, k]) => [squash(a), k] as const)]);
/** Accepts V2 template headers and V1 headers (snake_case or camelCase). */
export const canonicalHeader = (h: string): string => BY_KEY.get(squash(h.toLowerCase())) ?? h;

export function parseBool(raw: string | undefined): boolean | null | undefined {
  const s = (raw ?? "").trim().toLowerCase();
  if (!s) return null;
  if (["yes", "y", "true", "1", "☑"].includes(s)) return true;
  if (["no", "n", "false", "0", "☐"].includes(s)) return false;
  return undefined;
}
const NAME = /^[\p{L}\p{M}][\p{L}\p{M}' .’-]{0,59}$/u;
export interface Parsed { [column: string]: string | number | boolean | null }
export interface CheckOptions { lookup: EnumLookup; requireExternalId: boolean; externalIdLabel?: string | null; partial?: boolean }

/** Checks one person. Every problem is reported on its own field; nothing is silently changed or dropped. */
export function checkTrainee(v: Record<string, string>, o: CheckOptions): { row: Parsed; issues: Issue[] } {
  const issues: Issue[] = [], row: Parsed = {};
  const err = (field: string, code: string, message: string) => issues.push({ field, code, message, severity: "error" });
  const warn = (field: string, code: string, message: string) => issues.push({ field, code, message, severity: "warning" });
  const has = (k: string) => (v[k] ?? "").trim() !== "";
  const want = (k: string) => !o.partial || k in v;
  for (const c of COLUMNS) {
    if (c.required && want(c.key) && !has(c.key)) err(c.key, "REQUIRED", "This is required.");
    if (c.max && (v[c.key] ?? "").length > c.max) err(c.key, "TOO_LONG", `Use at most ${c.max} characters.`);
  }
  for (const [k, col] of [["first_name", "first_name"], ["father_name", "father_name"], ["grandfather_name", "grandfather_name"]] as const) if (has(k)) { const s = v[k]!.trim().replace(/\s+/g, " ").normalize("NFC"); if (!NAME.test(s)) err(k, "NAME_INVALID", "Use letters only, spaces, hyphen or apostrophe."); row[col] = s; }
  if (has("sex")) { const s = v["sex"]!.trim().toLowerCase(), sex = ["male", "m"].includes(s) ? "male" : ["female", "f"].includes(s) ? "female" : null; if (!sex) err("sex", "SEX_INVALID", "Use Male or Female."); row["sex"] = sex; row["sex_raw"] = v["sex"]!.trim(); }
  if (has("age")) { const n = Number(v["age"]); if (!Number.isInteger(n) || n < 10 || n > 80) err("age", "AGE_INVALID", "Enter the age in whole years."); else { row["age_years"] = n; if (n < 18 || n > 29) warn("age", "AGE_OUTSIDE", "The programme is for ages 18 to 29. This person will be marked not eligible."); } }
  if (has("form_date")) { const d = parseFormDate(v["form_date"]!); if (!d) err("form_date", "DATE_INVALID", "Use DD/MM/YYYY (day first), for example 25/03/2026."); else if (d > today()) err("form_date", "DATE_FUTURE", "The form date is in the future."); else { row["form_completion_date"] = d; row["form_date_confidence"] = "certain"; } }
  if (has("date_of_birth")) {
    const d = parseFormDate(v["date_of_birth"]!);
    if (!d) err("date_of_birth", "DOB_INVALID", "Use DD/MM/YYYY (day first), for example 25/03/2003.");
    else {
      Object.assign(row, { date_of_birth: d, dob_raw: v["date_of_birth"]!.trim() });
      const age = ageOn(d, (row["form_completion_date"] as string) ?? today());
      if (d > today()) err("date_of_birth", "DOB_FUTURE", "The birth date is in the future.");
      else if (typeof row["age_years"] === "number" && Math.abs(age - row["age_years"]) > 1) err("date_of_birth", "AGE_MISMATCH", `The birth date means ${age} years, but the age says ${row["age_years"]}.`);
    }
  }
  for (const [k, e164, raw] of [["phone", "phone_e164", "phone_raw"], ["phone_alternative", "phone_alt_e164", "phone_alt_raw"], ["emergency_contact_phone", "emergency_phone_e164", "emergency_phone_raw"]] as const) if (has(k)) { const p = parsePhone(v[k]!); if (!p.ok) err(k, p.code, p.message); else { row[e164] = p.e164; row[raw] = v[k]!.trim(); } }
  if (has("email")) { const e = v["email"]!.trim().toLowerCase(); if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) err("email", "EMAIL_INVALID", "Enter a valid email address."); row["email"] = e; }
  for (const [k, domain, code, raw, what] of [["region", "region", "region_code", "region_raw", "region"], ["education", "education", "education_code", "education_raw", "education level"], ["employment", "employment", "employment_code", "employment_raw", "employment status"], ["skill_usage", "skill_usage", "skill_usage_code", "skill_usage_raw", "answer"], ["plan", "plan", "plan_code", "plan_raw", "plan"], ["disability", "disability", "disability_code", "disability_raw", "disability type"]] as const)
    if (has(k)) { const x = o.lookup(domain, v[k]!); if (!x) err(k, "VALUE_UNKNOWN", `"${v[k]!.trim().slice(0, 40)}" is not a known ${what}.`); else { row[code] = x; row[raw] = v[k]!.trim(); } }
  for (const [k, col] of [["previously_participated", "previously_participated"], ["prior_completed", "prior_completed"], ["income_sufficient", "income_sufficient"], ["is_pwd", "is_pwd"], ["is_idp", "is_idp"], ["is_returnee", "is_returnee"], ["is_low_income", "is_low_income"], ["inclusion_none", "inclusion_none"], ["inclusion_prefer_not_to_say", "inclusion_prefer_not_say"], ["consent_accuracy", "consent_accuracy"], ["consent_followup", "consent_followup"], ["consent_contact_verify", "consent_contact_verify"], ["consent_image_use", "consent_image_use"]] as const)
    if (has(k)) { const b = parseBool(v[k]); if (b === undefined) err(k, "BOOLEAN_INVALID", "Use Yes or No."); else row[col] = b; }
  // Without these two the person cannot take part, so they are never registered (client decision R-6).
  for (const [k, what] of [["consent_accuracy", "that the information is correct"], ["consent_contact_verify", "that employment may be verified"]] as const) if (want(k) && row[k] === false) err(k, "CONSENT_REFUSED", `The trainee did not agree ${what}, so they cannot be registered.`);
  if (row["disability_code"] && row["is_pwd"] === undefined) row["is_pwd"] = !["not_pwd", "prefer_not_say"].includes(row["disability_code"] as string);
  if (has("prior_year_completed")) { const y = Number(v["prior_year_completed"]); if (!Number.isInteger(y) || y < 1950 || y > 2100) err("prior_year_completed", "YEAR_INVALID", "Enter a four-digit year."); else row["prior_year_completed"] = y; }
  for (const [k, col] of [["woreda", "woreda"], ["kebele", "kebele"], ["sub_city", "sub_city"], ["emergency_contact_name", "emergency_contact_name"], ["prior_training_type", "prior_training_type"], ["plan_other", "plan_other_text"], ["disability_other", "disability_other_text"], ["external_beneficiary_id", "external_beneficiary_id"]] as const) if (has(k)) row[col] = v[k]!.trim();
  if (o.requireExternalId && want("external_beneficiary_id") && !has("external_beneficiary_id")) err("external_beneficiary_id", "REQUIRED", `${o.externalIdLabel ?? "The provider beneficiary ID"} is required.`);
  if (has("roster_status")) { const r = v["roster_status"]!.trim().toLowerCase(), x = r === "active" ? "active" : ["reserve", "backup"].includes(r) ? "reserve" : null; if (!x) err("roster_status", "ROSTER_INVALID", "Use Active or Reserve."); else row["roster_status"] = x; }
  return { row, issues };
}
