import { mkdir, copyFile, readFile, readdir, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import path from "node:path";

const root = process.cwd();
const sourceDir = path.join(root, "images", "facebook-060426");
const manifestPath = path.join(root, "tmp", "facebook-060426-manifest.json");
const targetDir = path.join(root, "public", "images", "family-lab", "facebook-060426");
const targetManifest = path.join(targetDir, "manifest.json");

const supported = new Set([".jpg", ".jpeg", ".png", ".webp", ".gif"]);

function titleFromFilename(filename) {
  const stem = path.parse(filename).name;
  return stem
    .replace(/^\d+_[0-9a-z]+_/i, "")
    .replace(/[_-]+/g, " ")
    .replace(/\s+/g, " ")
    .trim() || "Untitled Photo";
}

function fallbackRowsFromFiles(files) {
  return files.map((filename) => ({
    filename,
    title: titleFromFilename(filename),
    description: "Family archive snapshot awaiting fuller annotation.",
    tags: ["family"],
    duplicate_of: null,
    named_file: !/^\d{6,}_/.test(filename) && !/^unnamed/i.test(filename),
  }));
}

async function main() {
  await mkdir(targetDir, { recursive: true });

  const sourceFiles = (await readdir(sourceDir))
    .filter((filename) => supported.has(path.extname(filename).toLowerCase()))
    .sort((a, b) => a.localeCompare(b));

  let rows;
  if (existsSync(manifestPath)) {
    rows = JSON.parse(await readFile(manifestPath, "utf-8"));
  } else {
    rows = fallbackRowsFromFiles(sourceFiles);
  }

  const uniqueRows = rows
    .filter((row) => !row.duplicate_of)
    .map((row) => ({
      ...row,
      src: `/images/family-lab/facebook-060426/${row.filename}`,
    }));

  for (const row of uniqueRows) {
    await copyFile(path.join(sourceDir, row.filename), path.join(targetDir, row.filename));
  }

  await writeFile(targetManifest, `${JSON.stringify(uniqueRows, null, 2)}\n`, "utf-8");
  console.log(`Family lab synced: ${uniqueRows.length} unique photos`);
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
