#!/usr/bin/env tsx
/**
 * STEG 2 — importera verifierade gap-fill-recept i seed-katalogen.
 *
 * - Läser export-JSON från gapfill-nullcells-export.json.
 * - Upsertar mot befintliga SEED_RECIPES på slug.
 * - Regenererar packages/database/src/seed/data/verified-recipes.ts programmatiskt.
 * - Hand-editerar ALDRIG verified-recipes.ts.
 */

import { SEED_RECIPES, type SeedRecipe } from "../../database/src/seed/data/recipes.js";
import * as fs from "node:fs/promises";
import * as path from "node:path";

const EXPORT_PATH = path.resolve(
  import.meta.dirname ?? "..",
  "..",
  "output",
  "gapfill-nullcells-export.json",
);

const VERIFIED_RECIPES_PATH = path.resolve(
  import.meta.dirname ?? "..",
  "..",
  "..",
  "database",
  "src",
  "seed",
  "data",
  "verified-recipes.ts",
);

interface ExportEnvelope {
  recipes: SeedRecipe[];
}

async function main() {
  const raw = await fs.readFile(EXPORT_PATH, "utf-8");
  const envelope: ExportEnvelope = JSON.parse(raw);
  const newRecipes = envelope.recipes;

  const existingBySlug = new Map(SEED_RECIPES.map((r) => [r.slug, r]));
  let upserted = 0;
  let added = 0;

  // Behåll befintlig ordning; nya läggs sist i export-ordning.
  const merged: SeedRecipe[] = [...SEED_RECIPES];

  for (const recipe of newRecipes) {
    if (existingBySlug.has(recipe.slug)) {
      const idx = merged.findIndex((r) => r.slug === recipe.slug);
      if (idx !== -1) merged[idx] = recipe;
      upserted++;
    } else {
      existingBySlug.set(recipe.slug, recipe);
      merged.push(recipe);
      added++;
    }
  }

  const fileBody = `import type {
  SeedRecipe,
} from "./recipes.js";

/**
 * Committed seed catalog: ${merged.length} verified recipes (JSON export converted once).
 * Allergens and nutrition are re-derived at seed time from canonical ingredients.
 * Verification statuses preserved: editorial + verified.
 */
export const VERIFIED_RECIPES: SeedRecipe[] = ${JSON.stringify(merged, null, 2)};
`;

  await fs.writeFile(VERIFIED_RECIPES_PATH, fileBody, "utf-8");

  console.error(`[import-gapfill] Befintliga recept: ${SEED_RECIPES.length}`);
  console.error(`[import-gapfill] Nya recept:       ${newRecipes.length}`);
  console.error(`[import-gapfill] Upsertade:         ${upserted}`);
  console.error(`[import-gapfill] Tillagda:          ${added}`);
  console.error(`[import-gapfill] Nytt totalt:       ${merged.length}`);
  console.error(`[import-gapfill] Skrev:             ${VERIFIED_RECIPES_PATH}`);
}

main().catch((err) => {
  console.error("[import-gapfill] Fatal:", err);
  process.exit(1);
});
