import type { Prisma, PrismaClient } from "@prisma/client";
import { canonicalPhoneKey } from "./phoneNormalize.js";

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);
}

export async function loadExcludedPairKeys(db: PrismaClient, projectId: bigint): Promise<Set<string>> {
  const rows = await db.traineeDuplicateCandidate.findMany({
    where: { projectId, status: { in: ["dismissed", "confirmed_duplicate"] } },
    select: { dedupeKey: true },
  });
  return new Set(rows.map((r) => r.dedupeKey));
}

export async function clearPendingDuplicateCandidates(db: PrismaClient, projectId: bigint): Promise<number> {
  const result = await db.traineeDuplicateCandidate.deleteMany({
    where: { projectId, status: "pending" },
  });
  return result.count;
}

const traineeSelect = {
  id: true,
  trainingProviderId: true,
  firstName: true,
  fatherName: true,
  grandfatherName: true,
  sex: true,
  ageYears: true,
  dateOfBirthEtCalendar: true,
  phonePrimary: true,
  phoneAlternative: true,
  emergencyContactPhone: true,
  externalBeneficiaryId: true,
  region: true,
} satisfies Prisma.TraineeSelect;

export async function loadTraineesForDuplicateScan(
  db: PrismaClient,
  projectId: bigint,
  traineeIds?: bigint[],
): Promise<TraineeDuplicateRecord[]> {
  return db.trainee.findMany({
    where: {
      projectId,
      ...(traineeIds?.length ? { id: { in: traineeIds } } : {}),
    },
    select: traineeSelect,
    orderBy: { id: "asc" },
  });
}

export async function persistDuplicateCandidates(
  db: PrismaClient,
  args: {
    projectId: bigint;
    scanRunId: bigint;
    pairs: ScoredPair[];
    now?: Date;
  },
): Promise<number> {
  const now = args.now ?? new Date();
  let upserted = 0;
  for (const pair of args.pairs) {
    const dedupeKey = pairDedupeKey(pair.traineeAId, pair.traineeBId);
    const existing = await db.traineeDuplicateCandidate.findUnique({
      where: { projectId_dedupeKey: { projectId: args.projectId, dedupeKey } },
      select: { id: true, status: true, score: true },
    });
    if (existing && existing.status !== "pending") continue;

    if (existing) {
      if (pair.score > existing.score) {
        await db.traineeDuplicateCandidate.update({
          where: { id: existing.id },
          data: {
            scanRunId: args.scanRunId,
            score: pair.score,
            matchSignals: pair.matchSignals as Prisma.InputJsonValue,
            lastSeenAt: now,
          },
        });
      } else {
        await db.traineeDuplicateCandidate.update({
          where: { id: existing.id },
          data: { lastSeenAt: now },
        });
      }
    } else {
      await db.traineeDuplicateCandidate.create({
        data: {
          projectId: args.projectId,
          scanRunId: args.scanRunId,
          traineeAId: pair.traineeAId,
          traineeBId: pair.traineeBId,
          dedupeKey,
          score: pair.score,
          matchSignals: pair.matchSignals as Prisma.InputJsonValue,
          status: "pending",
          firstSeenAt: now,
          lastSeenAt: now,
        },
      });
      upserted++;
    }
  }
  return upserted;
}

export type ImportPreviewInputRow = {
  rowNumber: number;
  firstName?: string;
  fatherName?: string;
  grandfatherName?: string;
  sex?: string;
  ageYears?: number;
  dateOfBirthEtCalendar?: string;
  phonePrimary?: string;
  phoneAlternative?: string;
  emergencyContactPhone?: string;
  externalBeneficiaryId?: string;
  region?: string;
  trainingProviderId?: string;
};

export function previewImportDuplicateMatches(
  dbTrainees: Array<TraineeDuplicateRecord & { traineeUniqueId?: string; providerName?: string }>,
  importRows: ImportPreviewInputRow[],
): ImportPreviewRow[] {
  const out: ImportPreviewRow[] = [];
  for (const row of importRows) {
    if (!row.trainingProviderId) continue;
    const pseudo: TraineeDuplicateRecord = {
      id: BigInt(-row.rowNumber),
      trainingProviderId: BigInt(row.trainingProviderId),
      firstName: row.firstName ?? "",
      fatherName: row.fatherName ?? null,
      grandfatherName: row.grandfatherName ?? null,
      sex: row.sex ?? "",
      ageYears: row.ageYears ?? null,
      dateOfBirthEtCalendar: row.dateOfBirthEtCalendar ?? null,
      phonePrimary: row.phonePrimary ?? null,
      phoneAlternative: row.phoneAlternative ?? null,
      emergencyContactPhone: row.emergencyContactPhone ?? null,
      externalBeneficiaryId: row.externalBeneficiaryId ?? null,
      region: row.region ?? null,
    };
    const matches: ImportPreviewRow["matches"] = [];
    for (const existing of dbTrainees) {
      const { score, matchSignals } = scoreTraineePair(pseudo, existing);
      const risk = riskLevelFromScore(score);
      if (!risk) continue;
      matches.push({
        traineeId: existing.id.toString(),
        traineeUniqueId: existing.traineeUniqueId ?? existing.id.toString(),
        traineeName: [existing.firstName, existing.fatherName, existing.grandfatherName].filter(Boolean).join(" "),
        providerName: existing.providerName ?? "",
        score,
        riskLevel: risk,
        matchSignals,
      });
    }
    matches.sort((a, b) => b.score - a.score);
    if (matches.length) {
      out.push({
        rowNumber: row.rowNumber,
        traineeName: [pseudo.firstName, pseudo.fatherName, pseudo.grandfatherName].filter(Boolean).join(" "),
        matches: matches.slice(0, 5),
      });
    }
  }
  return out;
}
