/**
 * scripts/generate-blur-placeholders.ts
 *
 * Generates tiny (10x10) base64-encoded JPEG blur placeholders for the
 * two portrait images used in the profile section. The output is a
 * TypeScript module at `src/lib/blur-placeholders.ts` exporting the
 * data URLs as constants, which can be passed to next/image's
 * `blurDataURL` prop.
 *
 * Run with:  bun run scripts/generate-blur-placeholders.ts
 *            (or `bun run images:blur` via package.json)
 */

import sharp from "sharp";
import { readFile, writeFile, mkdir } from "node:fs/promises";
import { dirname, resolve } from "node:path";

const ROOT = resolve(import.meta.dirname, "..");
const SRC_IMAGES = [
  {
    in: resolve(ROOT, "public/brand/portrait.jpg"),
    constName: "PORTRAIT_BLUR",
  },
  {
    in: resolve(ROOT, "public/brand/portrait-lifestyle.jpg"),
    constName: "PORTRAIT_LIFESTYLE_BLUR",
  },
] as const;

const OUT_FILE = resolve(ROOT, "src/lib/blur-placeholders.ts");

async function makeBlur(path: string): Promise<string> {
  const buf = await readFile(path);
  // Downscale to 10x10 (cover-ish), blur, and encode as base64 JPEG.
  const tiny = await sharp(buf)
    .resize(10, 10, { fit: "cover", position: sharp.strategy.entropy })
    .blur(2)
    .jpeg({ quality: 55, progressive: false, mozjpeg: false })
    .toBuffer();
  return `data:image/jpeg;base64,${tiny.toString("base64")}`;
}

async function main() {
  console.log("→ Generating blur placeholders…");
  const entries: Array<{ constName: string; dataUrl: string }> = [];
  for (const { in: inPath, constName } of SRC_IMAGES) {
    const dataUrl = await makeBlur(inPath);
    entries.push({ constName, dataUrl });
    console.log(`  • ${constName}  (${dataUrl.length} bytes)  ← ${inPath}`);
  }

  const banner = [
    "/**",
    " * src/lib/blur-placeholders.ts",
    " *",
    " * AUTO-GENERATED by `bun run images:blur`.",
    " * Do not edit by hand — re-run the script after replacing the",
    " * source images in /public/brand/.",
    " *",
    " * Each constant is a tiny (10x10) base64 JPEG data URL suitable",
    " * for passing to next/image's `blurDataURL` prop.",
    " */",
  ].join("\n");

  const body = entries
    .map(
      (e) =>
        `export const ${e.constName}: string = ${JSON.stringify(e.dataUrl)};`
    )
    .join("\n");

  await mkdir(dirname(OUT_FILE), { recursive: true });
  await writeFile(OUT_FILE, `${banner}\n\n${body}\n`, "utf8");
  console.log(`→ Wrote ${OUT_FILE}`);
}

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