import { fal } from "@fal-ai/client";
import sharp from "sharp";
import { mkdir, readFile } from "node:fs/promises";
import path from "node:path";

if (!process.env.FAL_KEY) throw new Error("FAL_KEY is missing. Add it to .env.local.");

const root = process.cwd();
const config = JSON.parse(await readFile(path.join(root, "assets-generation/images.config.json"), "utf8"));
const outputDir = path.join(root, "public/generated/images");
await mkdir(outputDir, { recursive: true });

for (const asset of config) {
  process.stdout.write(`Generating ${asset.id}... `);
  const result = await fal.subscribe("fal-ai/flux/schnell", {
    input: {
      prompt: asset.prompt,
      image_size: asset.imageSize,
      num_inference_steps: 4,
      num_images: 1,
      seed: asset.seed,
      enable_safety_checker: true,
      output_format: "jpeg"
    }
  });
  const url = result.data?.images?.[0]?.url;
  if (!url) throw new Error(`No image returned for ${asset.id}`);
  const response = await fetch(url);
  if (!response.ok) throw new Error(`Could not download ${asset.id}: ${response.status}`);
  const source = Buffer.from(await response.arrayBuffer());
  await sharp(source).resize({ width: 1600, withoutEnlargement: true }).webp({ quality: 82 }).toFile(path.join(outputDir, `${asset.id}.webp`));
  process.stdout.write("done\n");
}

console.log(`Saved ${config.length} optimized assets to public/generated/images.`);
