/** Moved unchanged from V1 (traineeDuplicateDetection.ts) so both versions score pairs the same way. */

export const DUPLICATE_ALGORITHM_VERSION = "v3-fuzzy-name-parts";

export const MAX_TRAINEES_PER_SCAN = 20_000;
export const MIN_CANDIDATE_SCORE = 85;
/** Minimum Jaro-Winkler similarity per name part (e.g. Ribka/Rebka, Alene/Alana). */
export const NAME_PART_SIMILARITY_THRESHOLD = 0.85;

export type TraineeDuplicateRecord = {
  id: bigint;
  trainingProviderId: bigint;
  firstName: string;
  fatherName: string | null;
  grandfatherName: string | null;
  sex: string;
  ageYears: number | null;
  dateOfBirthEtCalendar: string | null;
  phonePrimary: string | null;
  phoneAlternative: string | null;
  emergencyContactPhone: string | null;
  externalBeneficiaryId: string | null;
  region: string | null;
};

export type MatchSignals = {
  firstNameSimilarity?: number;
  fatherNameSimilarity?: number;
  grandfatherNameSimilarity?: number;
  samePhone?: boolean;
  reasons?: string[];
};

export type ScoredPair = {
  traineeAId: bigint;
  traineeBId: bigint;
  score: number;
  matchSignals: MatchSignals;
};

export type ImportPreviewRow = {
  rowNumber: number;
  traineeName: string;
  matches: Array<{
    traineeId: string;
    traineeUniqueId: string;
    traineeName: string;
    providerName: string;
    score: number;
    riskLevel: RiskLevel;
    matchSignals: MatchSignals;
  }>;
};

export type RiskLevel = "high" | "medium" | "low";

export function riskLevelFromScore(score: number): RiskLevel | null {
  if (score >= 95) return "high";
  if (score >= MIN_CANDIDATE_SCORE) return "medium";
  return null;
}

export function pairDedupeKey(aId: bigint, bId: bigint): string {
  const a = aId.toString();
  const b = bId.toString();
  return a < b ? `${a}::${b}` : `${b}::${a}`;
}

export function normalizePersonName(value: string | null | undefined): string {
  return String(value ?? "")
    .toLowerCase()
    .normalize("NFKD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/[^a-z0-9\s]/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

/** Jaro-Winkler similarity in [0, 1]. */
export function jaroWinklerSimilarity(a: string, b: string): number {
  if (!a && !b) return 1;
  if (!a || !b) return 0;
  if (a === b) return 1;

  const aLen = a.length;
  const bLen = b.length;
  const matchDistance = Math.max(Math.floor(Math.max(aLen, bLen) / 2) - 1, 0);
  const aMatches = new Array<boolean>(aLen).fill(false);
  const bMatches = new Array<boolean>(bLen).fill(false);
  let matches = 0;

  for (let i = 0; i < aLen; i++) {
    const start = Math.max(0, i - matchDistance);
    const end = Math.min(i + matchDistance + 1, bLen);
    for (let j = start; j < end; j++) {
      if (bMatches[j] || a[i] !== b[j]) continue;
      aMatches[i] = true;
      bMatches[j] = true;
      matches++;
      break;
    }
  }
  if (matches === 0) return 0;

  let transpositions = 0;
  let k = 0;
  for (let i = 0; i < aLen; i++) {
    if (!aMatches[i]) continue;
    while (!bMatches[k]) k++;
    if (a[i] !== b[k]) transpositions++;
    k++;
  }

  const jaro =
    (matches / aLen + matches / bLen + (matches - transpositions / 2) / matches) / 3;

  let prefix = 0;
  for (let i = 0; i < Math.min(4, aLen, bLen); i++) {
    if (a[i] === b[i]) prefix++;
    else break;
  }
  return jaro + prefix * 0.1 * (1 - jaro);
}

function levenshteinDistance(a: string, b: string): number {
  const rows = a.length + 1;
  const cols = b.length + 1;
  const matrix = Array.from({ length: rows }, () => new Array<number>(cols).fill(0));
  for (let i = 0; i < rows; i++) matrix[i]![0] = i;
  for (let j = 0; j < cols; j++) matrix[0]![j] = j;
  for (let i = 1; i < rows; i++) {
    for (let j = 1; j < cols; j++) {
      const cost = a[i - 1] === b[j - 1] ? 0 : 1;
      matrix[i]![j] = Math.min(
        matrix[i - 1]![j]! + 1,
        matrix[i]![j - 1]! + 1,
        matrix[i - 1]![j - 1]! + cost,
      );
    }
  }
  return matrix[a.length]![b.length]!;
}

/** True when two name parts are exact, JW-similar, or one small typo apart (e.g. Alene/Alana). */
export function namePartsAreClose(a: string, b: string): { similar: boolean; similarity: number } {
  if (!a && !b) return { similar: true, similarity: 1 };
  if (!a || !b) return { similar: false, similarity: 0 };
  if (a === b) return { similar: true, similarity: 1 };
  const jw = jaroWinklerSimilarity(a, b);
  if (jw >= NAME_PART_SIMILARITY_THRESHOLD) return { similar: true, similarity: jw };
  const dist = levenshteinDistance(a, b);
  const maxLen = Math.max(a.length, b.length);
  const maxDist = maxLen <= 6 ? 2 : 1;
  if (maxLen >= 3 && dist <= maxDist) {
    return { similar: true, similarity: Math.max(jw, 0.82) };
  }
  return { similar: false, similarity: jw };
}

type NamePartComparison = {
  label: string;
  similarity: number;
  exact: boolean;
};

function compareNamePart(
  a: string | null | undefined,
  b: string | null | undefined,
  label: string,
): NamePartComparison | null {
  const na = normalizePersonName(a);
  const nb = normalizePersonName(b);
  if (!na || !nb) return null;
  const { similar, similarity } = namePartsAreClose(na, nb);
  if (!similar) return null;
  return { label, similarity, exact: na === nb };
}

function formatPartReason(part: NamePartComparison): string {
  if (part.exact) return `Same ${part.label}`;
  return `Similar ${part.label} (${Math.round(part.similarity * 100)}%)`;
}

/**
 * Duplicate when first name and father name are each exact or closely similar.
 * Grandfather name is included when both trainees have one.
 * Phone is recorded only as extra context — never on its own.
 */
export function scoreTraineePair(
  a: TraineeDuplicateRecord,
  b: TraineeDuplicateRecord,
): { score: number; matchSignals: MatchSignals } {
  const signals: MatchSignals = { reasons: [] };

  const first = compareNamePart(a.firstName, b.firstName, "first name");
  const father = compareNamePart(a.fatherName, b.fatherName, "father name");
  if (!first || !father) {
    return { score: 0, matchSignals: signals };
  }

  const comparisons: NamePartComparison[] = [first, father];
  const grandA = normalizePersonName(a.grandfatherName);
  const grandB = normalizePersonName(b.grandfatherName);
  if (grandA && grandB) {
    const grandfather = compareNamePart(a.grandfatherName, b.grandfatherName, "grandfather name");
    if (!grandfather) {
      return { score: 0, matchSignals: signals };
    }
    comparisons.push(grandfather);
  }

  signals.firstNameSimilarity = Math.round(first.similarity * 100) / 100;
  signals.fatherNameSimilarity = Math.round(father.similarity * 100) / 100;
  const grandfather = comparisons[2];
  if (grandfather) {
    signals.grandfatherNameSimilarity = Math.round(grandfather.similarity * 100) / 100;
  }

  signals.reasons!.push(...comparisons.map(formatPartReason));

  const phoneA = canonicalPhoneKey(a.phonePrimary);
  const phoneB = canonicalPhoneKey(b.phonePrimary);
  const samePhone = Boolean(phoneA && phoneB && phoneA === phoneB);
  if (samePhone) {
    signals.samePhone = true;
    signals.reasons!.push("Same phone");
  }

  const avgSimilarity =
    comparisons.reduce((sum, part) => sum + part.similarity, 0) / comparisons.length;
  const score = Math.min(100, Math.round(avgSimilarity * 100));
  return { score: samePhone ? Math.min(100, score + 5) : score, matchSignals: signals };
}

function namePrefix(value: string | null | undefined, len: number): string | null {
  const normalized = normalizePersonName(value);
  return normalized.length >= 2 ? normalized.slice(0, len) : null;
}

export function buildComparisonBuckets(trainees: TraineeDuplicateRecord[]): Map<string, number[]> {
  const buckets = new Map<string, number[]>();
  const add = (key: string | null, index: number) => {
    if (!key) return;
    const arr = buckets.get(key) ?? [];
    arr.push(index);
    buckets.set(key, arr);
  };

  trainees.forEach((t, index) => {
    const first = namePrefix(t.firstName, 3);
    const father = namePrefix(t.fatherName, 3);
    const grandfather = namePrefix(t.grandfatherName, 3);
    add(first ? `fn:${first}` : null, index);
    add(father ? `fa:${father}` : null, index);
    add(grandfather ? `gn:${grandfather}` : null, index);
    if (first && father) add(`nf:${first[0]}${father[0]}`, index);
  });

  return buckets;
}

export function findCandidatePairs(
  trainees: TraineeDuplicateRecord[],
  excludedKeys: Set<string>,
): ScoredPair[] {
  if (trainees.length > MAX_TRAINEES_PER_SCAN) {
    throw Object.assign(new Error(`Scan exceeds ${MAX_TRAINEES_PER_SCAN} trainees. Narrow scope or contact support.`), {
      status: 422,
    });
  }

  const buckets = buildComparisonBuckets(trainees);
  const pairScores = new Map<string, ScoredPair>();

  for (const indices of buckets.values()) {
    if (indices.length < 2) continue;
    const unique = [...new Set(indices)].sort((x, y) => x - y);
    for (let i = 0; i < unique.length; i++) {
      for (let j = i + 1; j < unique.length; j++) {
        const a = trainees[unique[i]!]!;
        const b = trainees[unique[j]!]!;
        const key = pairDedupeKey(a.id, b.id);
        if (excludedKeys.has(key)) continue;
        const { score, matchSignals } = scoreTraineePair(a, b);
        if (score < MIN_CANDIDATE_SCORE) continue;
        const existing = pairScores.get(key);
        if (!existing || score > existing.score) {
          const [traineeAId, traineeBId] = a.id < b.id ? [a.id, b.id] : [b.id, a.id];
          pairScores.set(key, { traineeAId, traineeBId, score, matchSignals });
        }
      }
    }
  }

  return [...pairScores.values()].sort((x, y) => y.score - x.score);
}

function canonicalPhoneKey(v: unknown): string | null {
  const raw = String(v ?? "").trim();
  if (!raw) return null;
  let digits = raw.replace(/\D/g, "");
  if (!digits) return null;
  if (digits.startsWith("251") && digits.length >= 12) digits = digits.slice(-9);
  else if (digits.startsWith("251") && digits.length === 11) digits = digits.slice(-9);
  else if (digits.startsWith("0") && digits.length === 10) digits = digits.slice(1);
  if (digits.length === 9 && digits.startsWith("9")) return digits;
  return digits;
}
