import { INGREDIENT_LABEL_SYNONYMS_EN, INGREDIENT_LABEL_SYNONYMS_FR } from "@batch-cooking/shared";
import { expect } from "chai";
import { prisma } from "../../src/db/prisma.js";
import {
  extractQuantity,
  findIngredientMentions,
  type IngredientMatchEntry,
  loadIngredientCatalog,
  loadUnitCatalog,
  matchIngredientName,
  matchUnit,
  type UnitMatchEntry,
} from "../../src/lib/recipe-matching/ingredient-matcher.js";
import { resetDatabase } from "../../test-support/reset-db.js";

describe("ingredient-matcher", () => {
  describe("matchIngredientName", () => {
    const tomato: IngredientMatchEntry = { ingredientId: 1, label: "Tomato" };
    const chicken: IngredientMatchEntry = { ingredientId: 2, label: "Chicken" };
    const chickenBreast: IngredientMatchEntry = { ingredientId: 3, label: "Chicken breast" };
    const onion: IngredientMatchEntry = { ingredientId: 4, label: "Onion" };
    const allPurposeFlour: IngredientMatchEntry = { ingredientId: 5, label: "All-purpose flour" };
    const catalog = [tomato, chicken, chickenBreast, onion, allPurposeFlour];

    it("matches an exact single-word label", () => {
      expect(matchIngredientName("tomato", catalog)).to.equal(tomato.ingredientId);
    });

    it("is case- and accent-insensitive", () => {
      expect(matchIngredientName("TOMATO", catalog)).to.equal(tomato.ingredientId);
      expect(matchIngredientName("Tömato", catalog)).to.equal(tomato.ingredientId);
    });

    it("tolerates a regular plural", () => {
      expect(matchIngredientName("tomatoes", catalog)).to.equal(tomato.ingredientId);
      expect(matchIngredientName("onions", catalog)).to.equal(onion.ingredientId);
    });

    it("tolerates extra descriptive words around the match", () => {
      expect(matchIngredientName("2 large diced yellow onions", catalog)).to.equal(
        onion.ingredientId,
      );
    });

    it("prefers the more specific multi-word label over a shorter one it contains", () => {
      expect(matchIngredientName("boneless skinless chicken breasts", catalog)).to.equal(
        chickenBreast.ingredientId,
      );
    });

    it("still matches the shorter label when the more specific one isn't mentioned", () => {
      expect(matchIngredientName("diced chicken thighs", catalog)).to.equal(chicken.ingredientId);
    });

    it("matches a hyphenated multi-word label", () => {
      expect(matchIngredientName("2 cups all-purpose flour", catalog)).to.equal(
        allPurposeFlour.ingredientId,
      );
    });

    it("doesn't false-positive a short label inside an unrelated longer word", () => {
      // "egg" must not match inside "eggplant" — whole-token comparison, not substring.
      const eggplant: IngredientMatchEntry = { ingredientId: 6, label: "Eggplant" };
      const egg: IngredientMatchEntry = { ingredientId: 7, label: "Egg" };
      expect(matchIngredientName("eggplant", [egg, eggplant])).to.equal(eggplant.ingredientId);
    });

    it("returns null when nothing matches", () => {
      expect(matchIngredientName("mango", catalog)).to.equal(null);
    });

    it("returns null for an empty catalog", () => {
      expect(matchIngredientName("tomato", [])).to.equal(null);
    });

    it("returns null for an empty name", () => {
      expect(matchIngredientName("", catalog)).to.equal(null);
    });

    it("matches an alternate wording of the same ingredient via a second catalog entry sharing its ingredientId (issue #54)", () => {
      const vanillaBean: IngredientMatchEntry = { ingredientId: 8, label: "Vanilla bean" };
      const vanillaBeanSynonym: IngredientMatchEntry = { ingredientId: 8, label: "Vanilla pod" };
      const synonymCatalog = [vanillaBean, vanillaBeanSynonym];

      expect(matchIngredientName("1 vanilla pod", synonymCatalog)).to.equal(8);
      expect(matchIngredientName("1 vanilla bean", synonymCatalog)).to.equal(8);
    });

    it("breaks a same-specificity tie by the lowest ingredientId", () => {
      const onionA: IngredientMatchEntry = { ingredientId: 20, label: "Onion" };
      const onionB: IngredientMatchEntry = { ingredientId: 21, label: "Onion" };
      expect(matchIngredientName("onion", [onionB, onionA])).to.equal(20);
    });

    describe("locale: fr", () => {
      const carotte: IngredientMatchEntry = { ingredientId: 30, label: "Carotte" };
      const poulet: IngredientMatchEntry = { ingredientId: 31, label: "Poulet" };
      const blancDePoulet: IngredientMatchEntry = { ingredientId: 32, label: "Blanc de poulet" };
      const frCatalog = [carotte, poulet, blancDePoulet];

      it("tolerates a regular French plural (a bare 's', unlike English's several suffix patterns)", () => {
        // Regression case: French plurals like "carottes" end in "es", which
        // the English stemmer's own "es" rule would wrongly strip down to
        // "carott" (losing the "e" that's part of the singular "carotte")
        // — see stemWordFr's own doc comment. Locale "fr" must use the
        // French stemmer instead, or this never matches.
        expect(matchIngredientName("carottes", frCatalog, "fr")).to.equal(carotte.ingredientId);
      });

      it("is accent-insensitive the same way the English path is", () => {
        expect(matchIngredientName("CAROTTES", frCatalog, "fr")).to.equal(carotte.ingredientId);
      });

      it("tolerates extra descriptive words around the match", () => {
        expect(matchIngredientName("2 carottes râpées", frCatalog, "fr")).to.equal(
          carotte.ingredientId,
        );
      });

      it("prefers the more specific multi-word label over a shorter one it contains", () => {
        expect(matchIngredientName("blancs de poulet fermier", frCatalog, "fr")).to.equal(
          blancDePoulet.ingredientId,
        );
      });

      it("defaults to the English stemmer when no locale is passed — 'fr' text needs to opt in explicitly", () => {
        // Without locale: "fr", "carottes" stems via the English rules
        // (endsWith("es") -> strip 2 chars) into "carott", which doesn't
        // equal the catalog's own (also English-stemmed) "carotte" — no
        // match. This is the exact bug locale-aware stemming fixes; this
        // test pins down that the *default* stays exactly as it was for
        // every pre-existing English-only caller.
        expect(matchIngredientName("carottes", frCatalog)).to.equal(null);
      });
    });
  });

  describe("matchUnit", () => {
    const gram: UnitMatchEntry = { unitId: 1, synonyms: ["g", "gram", "grams"] };
    const tablespoon: UnitMatchEntry = {
      unitId: 2,
      synonyms: ["tbsp", "tbs", "tablespoon", "tablespoons"],
    };
    const cup: UnitMatchEntry = { unitId: 3, synonyms: ["cup", "cups"] };
    const catalog = [gram, tablespoon, cup];

    it("matches a full word synonym", () => {
      expect(matchUnit("tablespoon", catalog)).to.equal(tablespoon.unitId);
    });

    it("matches an abbreviation synonym", () => {
      expect(matchUnit("tbsp", catalog)).to.equal(tablespoon.unitId);
    });

    it("matches a plural synonym via the same stemming as ingredients", () => {
      expect(matchUnit("cups", catalog)).to.equal(cup.unitId);
    });

    it("is case-insensitive", () => {
      expect(matchUnit("TBSP", catalog)).to.equal(tablespoon.unitId);
    });

    it("ignores trailing text after the unit word", () => {
      expect(matchUnit("cup flour", catalog)).to.equal(cup.unitId);
    });

    it("also finds the unit word when it isn't first — unlike before French support existed, this is no longer only a first-word check (see the function's own doc comment)", () => {
      expect(matchUnit("a heaped tablespoon of sugar", catalog)).to.equal(tablespoon.unitId);
    });

    it("doesn't match a short abbreviation inside an unrelated word", () => {
      // "g" alone must not match "grated" — whole-token comparison.
      expect(matchUnit("grated", catalog)).to.equal(null);
    });

    it("returns null when nothing matches", () => {
      expect(matchUnit("pound", catalog)).to.equal(null);
    });

    it("returns null for an empty catalog", () => {
      expect(matchUnit("cup", [])).to.equal(null);
    });

    it("returns null for an empty string", () => {
      expect(matchUnit("", catalog)).to.equal(null);
    });

    describe("locale: fr", () => {
      const gramme: UnitMatchEntry = { unitId: 40, synonyms: ["g", "gr", "gramme", "grammes"] };
      const cuillereASoupe: UnitMatchEntry = {
        unitId: 41,
        synonyms: ["cuillère à soupe", "cuillères à soupe", "càs"],
      };
      const frCatalog = [gramme, cuillereASoupe];

      it("matches a genuinely multi-word synonym — the bug this locale support fixes: the old single-first-token check could never equal a whole multi-word phrase", () => {
        expect(matchUnit("cuillères à soupe de farine", frCatalog, "fr")).to.equal(
          cuillereASoupe.unitId,
        );
      });

      it("matches a single-word abbreviation the same way English units do", () => {
        expect(matchUnit("càs de farine", frCatalog, "fr")).to.equal(cuillereASoupe.unitId);
      });

      it("is accent-insensitive", () => {
        expect(matchUnit("2 CUILLÈRES À SOUPE de farine", frCatalog, "fr")).to.equal(
          cuillereASoupe.unitId,
        );
      });

      it("doesn't match a multi-word phrase against unrelated text mentioning the same first word alone", () => {
        expect(matchUnit("cuillère de bois", frCatalog, "fr")).to.equal(null);
      });
    });
  });

  describe("extractQuantity", () => {
    it("extracts a plain integer", () => {
      expect(extractQuantity("2 onions")).to.deep.equal({ quantity: 2, remainder: "onions" });
    });

    it("extracts a decimal using a dot", () => {
      expect(extractQuantity("1.5 cups flour")).to.deep.equal({
        quantity: 1.5,
        remainder: "cups flour",
      });
    });

    it("extracts a decimal using a comma", () => {
      expect(extractQuantity("1,5 cups flour")).to.deep.equal({
        quantity: 1.5,
        remainder: "cups flour",
      });
    });

    it("extracts a simple fraction", () => {
      expect(extractQuantity("1/2 cup sugar")).to.deep.equal({
        quantity: 0.5,
        remainder: "cup sugar",
      });
    });

    it("extracts a mixed number", () => {
      expect(extractQuantity("1 1/2 cups sugar")).to.deep.equal({
        quantity: 1.5,
        remainder: "cups sugar",
      });
    });

    it("returns null quantity and the trimmed original text when there's no leading number", () => {
      expect(extractQuantity("salt to taste")).to.deep.equal({
        quantity: null,
        remainder: "salt to taste",
      });
    });

    it("trims surrounding whitespace", () => {
      expect(extractQuantity("  2 eggs  ")).to.deep.equal({ quantity: 2, remainder: "eggs" });
    });

    it("only takes the first number of a hyphenated range", () => {
      expect(extractQuantity("2-3 carrots")).to.deep.equal({
        quantity: 2,
        remainder: "-3 carrots",
      });
    });
  });

  describe("findIngredientMentions", () => {
    const butter: IngredientMatchEntry = { ingredientId: 1, label: "Butter" };
    const flour: IngredientMatchEntry = { ingredientId: 2, label: "Flour" };
    const egg: IngredientMatchEntry = { ingredientId: 3, label: "Egg" };
    const catalog = [butter, flour, egg];
    const gram: UnitMatchEntry = { unitId: 1, synonyms: ["g", "gram", "grams"] };
    const unitCatalog = [gram];

    it("finds a single mention with no quantity or unit", () => {
      const text = "melt the butter";
      const mentions = findIngredientMentions(text, catalog, unitCatalog);
      expect(mentions).to.have.length(1);
      const [mention] = mentions;
      expect(mention?.ingredientId).to.equal(butter.ingredientId);
      expect(text.slice(mention?.start, mention?.end)).to.equal("butter");
      expect(mention?.quantity).to.equal(null);
      expect(mention?.unitId).to.equal(null);
    });

    it('resolves a quantity and unit glued directly to the ingredient ("200g butter")', () => {
      const text = "add 200g butter";
      const [mention] = findIngredientMentions(text, catalog, unitCatalog);
      expect(mention?.ingredientId).to.equal(butter.ingredientId);
      expect(mention?.quantity).to.equal(200);
      expect(mention?.unitId).to.equal(gram.unitId);
    });

    it("finds several mentions in reading order, non-overlapping", () => {
      const text = "melt the butter then add the flour and an egg";
      const mentions = findIngredientMentions(text, catalog, unitCatalog);
      expect(mentions.map((mention) => mention.ingredientId)).to.deep.equal([
        butter.ingredientId,
        flour.ingredientId,
        egg.ingredientId,
      ]);
    });

    it("is case- and accent-insensitive", () => {
      const text = "MELT THE BUTTER";
      const [mention] = findIngredientMentions(text, catalog, unitCatalog);
      expect(mention?.ingredientId).to.equal(butter.ingredientId);
    });

    it("ignores an unrelated number earlier in the text (e.g. an oven temperature)", () => {
      const text = "preheat to 180 degrees then add the egg";
      const [mention] = findIngredientMentions(text, catalog, unitCatalog);
      expect(mention?.ingredientId).to.equal(egg.ingredientId);
      expect(mention?.quantity).to.equal(null);
    });

    it("returns an empty array when nothing in the catalog is mentioned", () => {
      expect(findIngredientMentions("stir well", catalog, unitCatalog)).to.deep.equal([]);
    });

    it("returns an empty array for empty text", () => {
      expect(findIngredientMentions("", catalog, unitCatalog)).to.deep.equal([]);
    });

    describe("locale: fr", () => {
      const beurre: IngredientMatchEntry = { ingredientId: 10, label: "Beurre" };
      const farine: IngredientMatchEntry = { ingredientId: 11, label: "Farine" };
      const frCatalog = [beurre, farine];
      const gramme: UnitMatchEntry = { unitId: 40, synonyms: ["g", "gr", "gramme", "grammes"] };
      const cuillereASoupe: UnitMatchEntry = {
        unitId: 41,
        synonyms: ["cuillère à soupe", "cuillères à soupe", "càs"],
      };
      const frUnitCatalog = [gramme, cuillereASoupe];

      it("resolves a quantity and unit before the ingredient, connected by 'de'", () => {
        const text = "faire fondre 50g de beurre";
        const [mention] = findIngredientMentions(text, frCatalog, frUnitCatalog, "fr");
        expect(mention?.ingredientId).to.equal(beurre.ingredientId);
        expect(mention?.quantity).to.equal(50);
        expect(mention?.unitId).to.equal(gramme.unitId);
        expect(text.slice(mention?.start, mention?.end)).to.equal("beurre");
      });

      it('resolves a multi-word unit connected by "d\'"', () => {
        const text = "ajouter 2 cuillères à soupe de farine";
        const [mention] = findIngredientMentions(text, frCatalog, frUnitCatalog, "fr");
        expect(mention?.ingredientId).to.equal(farine.ingredientId);
        expect(mention?.quantity).to.equal(2);
        expect(mention?.unitId).to.equal(cuillereASoupe.unitId);
      });

      it("is accent-insensitive", () => {
        const text = "FAIRE FONDRE LE BEURRE";
        const [mention] = findIngredientMentions(text, frCatalog, frUnitCatalog, "fr");
        expect(mention?.ingredientId).to.equal(beurre.ingredientId);
      });
    });
  });

  describe("loadIngredientCatalog / loadUnitCatalog", () => {
    beforeEach(async () => {
      await resetDatabase();
    });

    after(async () => {
      await prisma.$disconnect();
    });

    it("loads one entry per Ingredient that has an English label, plus one per alternate wording (INGREDIENT_LABEL_SYNONYMS_EN), keyed by real ingredientId", async () => {
      const tomato = await prisma.ingredient.findFirstOrThrow({ where: { key: "tomato" } });
      const vanillaBean = await prisma.ingredient.findFirstOrThrow({
        where: { key: "vanillaBean" },
      });
      const ingredientCount = await prisma.ingredient.count();
      const synonymCount = Object.values(INGREDIENT_LABEL_SYNONYMS_EN).reduce(
        (sum, synonyms) => sum + synonyms.length,
        0,
      );

      const catalog = await loadIngredientCatalog();

      // Every seeded ingredient has an authored English label (verified at
      // generation time — see packages/shared/src/data/catalog-labels-en.ts),
      // so nothing should be silently skipped — plus one extra entry per
      // synonym (issue #54), sharing the same ingredientId as the primary
      // label's entry.
      expect(catalog).to.have.length(ingredientCount + synonymCount);
      const tomatoEntry = catalog.find((entry) => entry.ingredientId === tomato.id);
      expect(tomatoEntry?.label).to.equal("Tomato");

      const vanillaBeanEntries = catalog.filter((entry) => entry.ingredientId === vanillaBean.id);
      expect(vanillaBeanEntries.map((entry) => entry.label)).to.deep.equal([
        "Vanilla bean",
        "Vanilla pod",
      ]);
    });

    it("loads one entry per Unit that has English synonyms, keyed by real unitId", async () => {
      const cup = await prisma.unit.findFirstOrThrow({ where: { key: "cup" } });
      const unitCount = await prisma.unit.count();

      const catalog = await loadUnitCatalog();

      expect(catalog).to.have.length(unitCount);
      const cupEntry = catalog.find((entry) => entry.unitId === cup.id);
      expect(cupEntry?.synonyms).to.deep.equal(["cup", "cups"]);
    });

    it("loads one entry per Ingredient that has a French label, plus one per alternate wording (INGREDIENT_LABEL_SYNONYMS_FR), keyed by real ingredientId", async () => {
      const carrot = await prisma.ingredient.findFirstOrThrow({ where: { key: "carrot" } });
      const vanillaBean = await prisma.ingredient.findFirstOrThrow({
        where: { key: "vanillaBean" },
      });
      const ingredientCount = await prisma.ingredient.count();
      const synonymCount = Object.values(INGREDIENT_LABEL_SYNONYMS_FR).reduce(
        (sum, synonyms) => sum + synonyms.length,
        0,
      );

      const catalog = await loadIngredientCatalog("fr");

      // Every seeded ingredient has an authored French label too (copied
      // from apps/web's fr locale — see catalog-labels-fr.ts's own doc
      // comment), so this mirrors the English test above 1:1.
      expect(catalog).to.have.length(ingredientCount + synonymCount);
      const carrotEntry = catalog.find((entry) => entry.ingredientId === carrot.id);
      expect(carrotEntry?.label).to.equal("Carotte");

      const vanillaBeanEntries = catalog.filter((entry) => entry.ingredientId === vanillaBean.id);
      expect(vanillaBeanEntries.map((entry) => entry.label)).to.deep.equal([
        "Vanille (gousse)",
        "Gousse de vanille",
      ]);
    });

    it("loads one entry per Unit that has French synonyms, keyed by real unitId", async () => {
      const cup = await prisma.unit.findFirstOrThrow({ where: { key: "cup" } });
      const unitCount = await prisma.unit.count();

      const catalog = await loadUnitCatalog("fr");

      expect(catalog).to.have.length(unitCount);
      const cupEntry = catalog.find((entry) => entry.unitId === cup.id);
      expect(cupEntry?.synonyms).to.deep.equal(["tasse", "tasses"]);
    });

    it("returns an empty catalog for a locale with no label table at all — the DB is still queried, there's just nothing in either table to match a row against", async () => {
      const ingredientCatalog = await loadIngredientCatalog("de");
      const unitCatalog = await loadUnitCatalog("de");

      expect(ingredientCatalog).to.deep.equal([]);
      expect(unitCatalog).to.deep.equal([]);
    });
  });
});
