import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, it } from "node:test";
import {
  MIN_CANDIDATE_SCORE,
  NAME_PART_SIMILARITY_THRESHOLD,
  jaroWinklerSimilarity,
  namePartsAreClose,
  normalizePersonName,
  riskLevelFromScore,
  scoreTraineePair,
  type TraineeDuplicateRecord,
} from "./traineeDuplicateDetection.js";
import {
  isScientificNotationPhone,
  isValidEthiopianMobilePhone,
  phonePrimaryValidationError,
} from "./phoneNormalize.js";

const baseTrainee = (overrides: Partial<TraineeDuplicateRecord> = {}): TraineeDuplicateRecord => ({
  id: 1n,
  trainingProviderId: 10n,
  firstName: "Rebka",
  fatherName: "Alene",
  grandfatherName: "Haile",
  sex: "female",
  ageYears: 25,
  dateOfBirthEtCalendar: "1999-01-15",
  phonePrimary: "0911223344",
  phoneAlternative: null,
  emergencyContactPhone: null,
  externalBeneficiaryId: null,
  region: "Addis Ababa",
  ...overrides,
});

describe("normalizePersonName", () => {
  it("lowercases, strips punctuation, and collapses whitespace", () => {
    assert.equal(normalizePersonName("  Rebka   Alene!  "), "rebka alene");
    assert.equal(normalizePersonName(null), "");
  });
});

describe("jaroWinklerSimilarity", () => {
  it("treats Ribka and Rebka as similar", () => {
    const sim = jaroWinklerSimilarity("ribka", "rebka");
    assert.ok(sim >= NAME_PART_SIMILARITY_THRESHOLD);
  });

  it("treats Alene and Alana as similar", () => {
    assert.equal(namePartsAreClose("alene", "alana").similar, true);
  });
});

describe("riskLevelFromScore", () => {
  it("maps name-match scores to risk levels", () => {
    assert.equal(riskLevelFromScore(100), "high");
    assert.equal(riskLevelFromScore(95), "high");
    assert.equal(riskLevelFromScore(MIN_CANDIDATE_SCORE), "medium");
    assert.equal(riskLevelFromScore(MIN_CANDIDATE_SCORE - 1), null);
  });
});

describe("scoreTraineePair", () => {
  it("matches Rebka Alene with Ribka Alene", () => {
    const a = baseTrainee({ id: 1n, firstName: "Rebka", fatherName: "Alene", grandfatherName: null });
    const b = baseTrainee({ id: 2n, firstName: "Ribka", fatherName: "Alene", grandfatherName: null });
    const { score } = scoreTraineePair(a, b);
    assert.ok(score >= MIN_CANDIDATE_SCORE);
  });

  it("matches Rebka Alene with Rebka Alana", () => {
    const a = baseTrainee({ id: 1n, firstName: "Rebka", fatherName: "Alene", grandfatherName: null });
    const b = baseTrainee({ id: 2n, firstName: "Rebka", fatherName: "Alana", grandfatherName: null });
    const { score } = scoreTraineePair(a, b);
    assert.ok(score >= MIN_CANDIDATE_SCORE);
  });

  it("includes grandfather name when both trainees have one", () => {
    const a = baseTrainee({ id: 1n, grandfatherName: "Haile" });
    const b = baseTrainee({ id: 2n, grandfatherName: "Haile", phonePrimary: "0922000000" });
    const { score, matchSignals } = scoreTraineePair(a, b);
    assert.ok(score >= MIN_CANDIDATE_SCORE);
    assert.equal(matchSignals.grandfatherNameSimilarity, 1);
  });

  it("does not match when first and father names are both different", () => {
    const a = baseTrainee({ id: 1n, firstName: "Sara", fatherName: "Hailu", grandfatherName: null });
    const b = baseTrainee({ id: 2n, firstName: "Daniel", fatherName: "Mekonnen", grandfatherName: null });
    const { score } = scoreTraineePair(a, b);
    assert.equal(score, 0);
  });

  it("does not match on phone alone", () => {
    const a = baseTrainee({ id: 1n, firstName: "Sara", fatherName: "Hailu", grandfatherName: null });
    const b = baseTrainee({
      id: 2n,
      firstName: "Daniel",
      fatherName: "Mekonnen",
      grandfatherName: null,
      phonePrimary: "0911111111",
    });
    const { score } = scoreTraineePair(a, b);
    assert.equal(score, 0);
  });
});

describe("phone validation", () => {
  it("rejects scientific notation phones", () => {
    assert.equal(isScientificNotationPhone("251940E+11"), true);
    assert.equal(isValidEthiopianMobilePhone("251940E+11"), false);
    assert.match(phonePrimaryValidationError("251940E+11") ?? "", /scientific notation/i);
  });

  it("accepts standard Ethiopian mobile formats", () => {
    assert.equal(isValidEthiopianMobilePhone("0911223344"), true);
    assert.equal(isValidEthiopianMobilePhone("+251911223344"), true);
    assert.equal(phonePrimaryValidationError("0911223344"), null);
  });
});

describe("import phone hard-block", () => {
  it("still rejects duplicate phonePrimary in project import route", () => {
    const here = dirname(fileURLToPath(import.meta.url));
    const domainSource = readFileSync(join(here, "../routes/domain.ts"), "utf8");
    const importStart = domainSource.indexOf('router.post("/projects/:projectId/trainees/import"');
    const importEnd = domainSource.indexOf("const created = await prisma.$transaction", importStart);
    const importBlock = domainSource.slice(importStart, importEnd);
    assert.match(importBlock, /phonePrimary already exists in this project/);
    assert.match(importBlock, /Duplicate phonePrimary in file/);
    assert.match(importBlock, /phonePrimaryValidationError/);
    assert.doesNotMatch(importBlock, /traineeDuplicateDetection/);
  });
});
