/** Merge partial/agent screenshot URL results into urls.json */
import { readdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";

const PNG_DIR = join(import.meta.dir, "../.picto-gradient-png");

const batchFiles = (await readdir(PNG_DIR))
    .filter((f) => f.startsWith("screenshot-batch-") && f.endsWith(".json"))
    .sort((a, b) => Number(a.match(/\d+/)?.[0]) - Number(b.match(/\d+/)?.[0]));

const expected: { fileName: string; nodeId: string }[] = [];
for (const f of batchFiles) {
    expected.push(...JSON.parse(await readFile(join(PNG_DIR, f), "utf8")));
}

const resultFiles = [
    "results-transparent-partial.json",
    "results-partial.json",
    ...(await readdir(PNG_DIR))
        .filter((f) => f.startsWith("results-agent-") && f.endsWith(".json"))
        .sort(),
];

const byName = new Map<string, string>();
for (const rf of resultFiles) {
    try {
        const entries: { fileName: string; url: string }[] = JSON.parse(
            await readFile(join(PNG_DIR, rf), "utf8"),
        );
        for (const e of entries) byName.set(e.fileName, e.url);
    } catch {
        // file may not exist yet
    }
}

const urls = expected.map(({ fileName }) => {
    const url = byName.get(fileName);
    if (!url) throw new Error(`Missing URL for ${fileName}`);
    return { fileName, url };
});

await writeFile(join(PNG_DIR, "urls.json"), `${JSON.stringify(urls, null, 2)}\n`);
console.log(`Merged ${urls.length} entries into urls.json`);
