import { canonicalPhoneKey } from "./phoneNormalize.js";

export type RosterInputRow = {
  rowNumber: number;
  class?: string;
  first_name?: string;
  firstName?: string;
  father_name?: string;
  fatherName?: string;
  phone?: string;
  email?: string;
  gender?: string;
  department?: string;
  [key: string]: unknown;
};

export type DbTraineeForRosterCheck = {
  id: bigint;
  traineeUniqueId: string;
  firstName: string;
  fatherName: string | null;
  email: string | null;
  phonePrimary: string | null;
  phoneAlternative: string | null;
  providerName: string;
};

export type RosterStatusCategory =
  | "internal_duplicate_phone"
  | "internal_duplicate_email"
  | "internal_duplicate_name"
  | "system_duplicate_phone"
  | "system_duplicate_email"
  | "system_duplicate_name"
  | "unverifiable_no_phone_or_email"
  | "unverifiable_by_phone"
  | "clean";

export type NormalizedRosterRow = {
  rowNumber: number;
  rowRef: string;
  classLabel: string;
  firstName: string;
  fatherName: string;
  uploadedName: string;
  phoneRaw: string;
  emailRaw: string;
  phoneClean: string | null;
  phoneValid: boolean;
  nameKey: string;
  emailKey: string | null;
  dataCompleteness: "both" | "phone_only" | "email_only" | "neither";
};

export type RosterReportRow = {
  rowRef: string;
  rowNumber: number;
  uploadedName: string;
  phone: string;
  phoneClean: string | null;
  email: string;
  dataCompleteness: string;
  status: string;
  statusCategory: RosterStatusCategory;
  internalClusterRefs: string | null;
  matchedName: string | null;
  matchedProvider: string | null;
  matchedRecordId: string | null;
  matchType: string | null;
};

export type RosterDuplicateCheckResult = {
  summary: Record<RosterStatusCategory | "totalRows", number> & { totalRows: number };
  internalClusters: Array<{
    matchType: "phone" | "email" | "name";
    confidence: "high" | "medium" | "low";
    rowRefs: string[];
  }>;
  items: RosterReportRow[];
};

const STATUS_SORT: Record<RosterStatusCategory, number> = {
  internal_duplicate_phone: 1,
  internal_duplicate_email: 2,
  internal_duplicate_name: 3,
  system_duplicate_phone: 4,
  system_duplicate_email: 5,
  system_duplicate_name: 6,
  unverifiable_no_phone_or_email: 7,
  unverifiable_by_phone: 8,
  clean: 9,
};

/** Strip Excel `.0` suffix before canonical phone normalization. */
export function normalizeRosterPhoneRaw(raw: unknown): { phoneClean: string | null; phoneValid: boolean } {
  let s = String(raw ?? "").trim();
  if (/\.0+$/.test(s)) s = s.replace(/\.0+$/, "");
  const key = canonicalPhoneKey(s);
  const phoneValid = Boolean(key && key.length === 9 && key.startsWith("9"));
  return { phoneClean: phoneValid ? key : key || null, phoneValid };
}

export function buildRosterNameKey(first: unknown, father: unknown): string {
  const parts = [first, father]
    .map((v) => String(v ?? "").trim().toLowerCase())
    .filter((v) => v.length > 0);
  return parts.join(" ").replace(/\s+/g, " ").trim();
}

export function buildRosterEmailKey(email: unknown): string | null {
  const s = String(email ?? "").trim().toLowerCase();
  return s || null;
}

function field(row: RosterInputRow, ...keys: string[]): string {
  for (const k of keys) {
    const v = row[k];
    if (v != null && String(v).trim()) return String(v).trim();
  }
  return "";
}

function rowRef(classLabel: string, rowNumber: number): string {
  return classLabel ? `${classLabel}#${rowNumber}` : `row#${rowNumber}`;
}

export function normalizeRosterRows(rows: RosterInputRow[]): NormalizedRosterRow[] {
  return rows.map((row) => {
    const firstName = field(row, "first_name", "firstName");
    const fatherName = field(row, "father_name", "fatherName");
    const classLabel = field(row, "class", "source_sheet", "sheet");
    const phoneRaw = field(row, "phone", "phone_primary", "phonePrimary");
    const emailRaw = field(row, "email");
    const { phoneClean, phoneValid } = normalizeRosterPhoneRaw(phoneRaw);
    const emailKey = buildRosterEmailKey(emailRaw);
    const hasPhone = phoneValid;
    const hasEmail = Boolean(emailKey);
    const dataCompleteness: NormalizedRosterRow["dataCompleteness"] = hasPhone && hasEmail
      ? "both"
      : hasPhone
        ? "phone_only"
        : hasEmail
          ? "email_only"
          : "neither";

    return {
      rowNumber: row.rowNumber,
      rowRef: rowRef(classLabel, row.rowNumber),
      classLabel,
      firstName,
      fatherName,
      uploadedName: [firstName, fatherName].filter(Boolean).join(" "),
      phoneRaw,
      emailRaw,
      phoneClean,
      phoneValid,
      nameKey: buildRosterNameKey(firstName, fatherName),
      emailKey,
      dataCompleteness,
    };
  });
}

function addToMap<T>(map: Map<string, T[]>, key: string, value: T) {
  const list = map.get(key) ?? [];
  list.push(value);
  map.set(key, list);
}

function buildDbIndexes(trainees: DbTraineeForRosterCheck[]) {
  const byPhone = new Map<string, DbTraineeForRosterCheck[]>();
  const byEmail = new Map<string, DbTraineeForRosterCheck[]>();
  const byName = new Map<string, DbTraineeForRosterCheck[]>();

  for (const t of trainees) {
    for (const phone of [t.phonePrimary, t.phoneAlternative]) {
      const key = canonicalPhoneKey(phone);
      if (key && key.length === 9 && key.startsWith("9")) addToMap(byPhone, key, t);
    }
    const emailKey = buildRosterEmailKey(t.email);
    if (emailKey) addToMap(byEmail, emailKey, t);
    const nameKey = buildRosterNameKey(t.firstName, t.fatherName ?? "");
    if (nameKey) addToMap(byName, nameKey, t);
  }

  return { byPhone, byEmail, byName };
}

function clusterLabel(refs: string[], selfRef: string): string {
  const others = refs.filter((r) => r !== selfRef);
  const all = refs.length;
  const parts = others.length ? others.join(", ") : refs.join(", ");
  return `Internal duplicate (${all}x: ${parts})`;
}

function traineeDisplayName(t: DbTraineeForRosterCheck): string {
  return [t.firstName, t.fatherName].filter(Boolean).join(" ");
}

export function runRosterDuplicateCheck(
  inputRows: RosterInputRow[],
  dbTrainees: DbTraineeForRosterCheck[],
): RosterDuplicateCheckResult {
  const normalized = normalizeRosterRows(inputRows);
  const { byPhone, byEmail, byName } = buildDbIndexes(dbTrainees);

  const phoneGroups = new Map<string, NormalizedRosterRow[]>();
  const emailGroups = new Map<string, NormalizedRosterRow[]>();
  const nameGroups = new Map<string, NormalizedRosterRow[]>();

  for (const row of normalized) {
    if (row.phoneValid && row.phoneClean) addToMap(phoneGroups, row.phoneClean, row);
    if (row.emailKey) addToMap(emailGroups, row.emailKey, row);
    if (row.nameKey) addToMap(nameGroups, row.nameKey, row);
  }

  const internalClusters: RosterDuplicateCheckResult["internalClusters"] = [];
  for (const [key, members] of phoneGroups) {
    if (members.length < 2) continue;
    internalClusters.push({
      matchType: "phone",
      confidence: "high",
      rowRefs: members.map((m) => m.rowRef),
    });
  }
  for (const [key, members] of emailGroups) {
    if (members.length < 2) continue;
    internalClusters.push({
      matchType: "email",
      confidence: "medium",
      rowRefs: members.map((m) => m.rowRef),
    });
  }
  for (const [key, members] of nameGroups) {
    if (members.length < 2) continue;
    internalClusters.push({
      matchType: "name",
      confidence: "low",
      rowRefs: members.map((m) => m.rowRef),
    });
  }

  const internalPhoneRefs = new Set(
    [...phoneGroups.values()].filter((g) => g.length >= 2).flatMap((g) => g.map((r) => r.rowRef)),
  );
  const internalEmailRefs = new Set(
    [...emailGroups.values()].filter((g) => g.length >= 2).flatMap((g) => g.map((r) => r.rowRef)),
  );
  const internalNameRefs = new Set(
    [...nameGroups.values()].filter((g) => g.length >= 2).flatMap((g) => g.map((r) => r.rowRef)),
  );

  const summary: RosterDuplicateCheckResult["summary"] = {
    totalRows: normalized.length,
    internal_duplicate_phone: 0,
    internal_duplicate_email: 0,
    internal_duplicate_name: 0,
    system_duplicate_phone: 0,
    system_duplicate_email: 0,
    system_duplicate_name: 0,
    unverifiable_no_phone_or_email: 0,
    unverifiable_by_phone: 0,
    clean: 0,
  };

  const items: RosterReportRow[] = normalized.map((row) => {
    let statusCategory: RosterStatusCategory = "clean";
    let status = "No match";
    let internalClusterRefs: string | null = null;
    let matchedName: string | null = null;
    let matchedProvider: string | null = null;
    let matchedRecordId: string | null = null;
    let matchType: string | null = null;

    if (internalPhoneRefs.has(row.rowRef)) {
      const refs = phoneGroups.get(row.phoneClean!)!.map((r) => r.rowRef);
      statusCategory = "internal_duplicate_phone";
      status = clusterLabel(refs, row.rowRef);
      internalClusterRefs = refs.join(", ");
      matchType = "phone";
    } else if (internalEmailRefs.has(row.rowRef)) {
      const refs = emailGroups.get(row.emailKey!)!.map((r) => r.rowRef);
      statusCategory = "internal_duplicate_email";
      status = clusterLabel(refs, row.rowRef);
      internalClusterRefs = refs.join(", ");
      matchType = "email";
    } else if (internalNameRefs.has(row.rowRef)) {
      const refs = nameGroups.get(row.nameKey)!.map((r) => r.rowRef);
      statusCategory = "internal_duplicate_name";
      status = `${clusterLabel(refs, row.rowRef)} — same name, verify same person`;
      internalClusterRefs = refs.join(", ");
      matchType = "name";
    } else {
      let systemHit: DbTraineeForRosterCheck | null = null;
      let systemMatchType: "phone" | "email" | "name" | null = null;

      if (row.phoneValid && row.phoneClean) {
        const hits = byPhone.get(row.phoneClean);
        if (hits?.length) {
          systemHit = hits[0]!;
          systemMatchType = "phone";
        }
      }
      if (!systemHit && row.emailKey) {
        const hits = byEmail.get(row.emailKey);
        if (hits?.length) {
          systemHit = hits[0]!;
          systemMatchType = "email";
        }
      }
      if (!systemHit && row.nameKey) {
        const hits = byName.get(row.nameKey);
        if (hits?.length) {
          systemHit = hits[0]!;
          systemMatchType = "name";
        }
      }

      if (systemHit && systemMatchType) {
        matchedName = traineeDisplayName(systemHit);
        matchedProvider = systemHit.providerName;
        matchedRecordId = systemHit.traineeUniqueId;
        matchType = systemMatchType;

        if (systemMatchType === "phone") {
          statusCategory = "system_duplicate_phone";
          status = "Duplicate in system";
        } else if (systemMatchType === "email") {
          statusCategory = "system_duplicate_email";
          status = "Duplicate in system (email match)";
        } else {
          statusCategory = "system_duplicate_name";
          status = "Possible duplicate in system (name match) — manual review";
        }
      } else if (row.dataCompleteness === "neither") {
        statusCategory = "unverifiable_no_phone_or_email";
        status = "Unverifiable — no phone or email";
        matchType = "name only";
      } else if (!row.phoneValid) {
        statusCategory = "unverifiable_by_phone";
        status = "Unverifiable by phone — no system match on email/name";
        matchType = row.emailKey ? "email" : "name only";
      } else {
        statusCategory = "clean";
        status = "No match";
      }
    }

    summary[statusCategory] += 1;

    return {
      rowRef: row.rowRef,
      rowNumber: row.rowNumber,
      uploadedName: row.uploadedName,
      phone: row.phoneRaw || "—",
      phoneClean: row.phoneClean,
      email: row.emailRaw || "—",
      dataCompleteness: row.dataCompleteness,
      status,
      statusCategory,
      internalClusterRefs,
      matchedName,
      matchedProvider,
      matchedRecordId,
      matchType,
    };
  });

  items.sort((a, b) => {
    const sa = STATUS_SORT[a.statusCategory];
    const sb = STATUS_SORT[b.statusCategory];
    return sa - sb || a.rowNumber - b.rowNumber;
  });

  return { summary, internalClusters, items };
}
