import { promises as fs } from "fs";
import path from "path";

const SOURCE = path.resolve("..", "media", "onboarding");
const ROOT = path.resolve("public", "media", "onboarding");
const MANIFEST = path.join(ROOT, "manifest.json");
const EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".webp"]);

async function walk(dir, base = "") {
  const entries = await fs.readdir(dir, { withFileTypes: true });
  const files = [];
  for (const entry of entries) {
    const full = path.join(dir, entry.name);
    const rel = path.join(base, entry.name);
    if (entry.isDirectory()) {
      files.push(...(await walk(full, rel)));
    } else if (EXTENSIONS.has(path.extname(entry.name).toLowerCase())) {
      files.push(rel.replace(/\\/g, "/"));
    }
  }
  return files;
}

async function ensureDir(dir) {
  await fs.mkdir(dir, { recursive: true });
}

async function exists(dir) {
  try {
    await fs.access(dir);
    return true;
  } catch {
    return false;
  }
}

async function main() {
  try {
    const sourceExists = await exists(SOURCE);
    const rootExists = await exists(ROOT);
    const source = sourceExists ? SOURCE : rootExists ? ROOT : null;
    await ensureDir(ROOT);
    const files = source ? await walk(source) : [];
    if (source && source !== ROOT) {
      for (const file of files) {
        const src = path.join(source, file);
        const dest = path.join(ROOT, file);
        await ensureDir(path.dirname(dest));
        await fs.copyFile(src, dest);
      }
    }
    const payload = {
      generated_at: new Date().toISOString(),
      files: files.sort(),
    };
    await fs.writeFile(MANIFEST, JSON.stringify(payload, null, 2));
  } catch (err) {
    console.error("Failed to build onboarding media manifest", err);
    process.exitCode = 1;
  }
}

await main();
