import { writeFile } from "node:fs/promises";
function ver(base) {
    const b = base.replace(/\/+$/, "");
    return b.endsWith("/v1") ? b : `${b}/v1`;
}
/** Map "WxH" to the nearest size the OpenAI image model accepts. */
function mapSize(model, size) {
    const [w, h] = (size ?? "1024x1024").split("x").map(Number);
    const aspect = w && h ? w / h : 1;
    const isDalle3 = /dall-?e-?3/i.test(model);
    if (aspect < 0.83)
        return isDalle3 ? "1024x1792" : "1024x1536"; // portrait
    if (aspect > 1.2)
        return isDalle3 ? "1792x1024" : "1536x1024"; // landscape
    return "1024x1024";
}
export async function generateImage(cfg, prompt, size, dest) {
    const res = await fetch(`${ver(cfg.baseUrl)}/images/generations`, {
        method: "POST",
        headers: { Authorization: `Bearer ${cfg.apiKey}`, "Content-Type": "application/json" },
        body: JSON.stringify({ model: cfg.model, prompt, size: mapSize(cfg.model, size), n: 1 }),
    });
    if (!res.ok) {
        throw new Error(`image gen HTTP ${res.status}: ${(await res.text().catch(() => "")).slice(0, 300)}`);
    }
    const json = (await res.json());
    const url = json.data?.[0]?.url;
    const b64 = json.data?.[0]?.b64_json;
    if (url) {
        const img = await fetch(url);
        if (!img.ok)
            throw new Error(`image download HTTP ${img.status}`);
        await writeFile(dest, new Uint8Array(await img.arrayBuffer()));
        return;
    }
    if (b64) {
        await writeFile(dest, Buffer.from(b64, "base64"));
        return;
    }
    throw new Error("image gen returned no url/b64");
}
//# sourceMappingURL=image-gen.js.map