import fs from "fs/promises";
import { Readable } from "stream";
export class GeneratedImage extends String {
    response;
    constructor(response) {
        super(response.url || "");
        this.response = response;
    }
    get url() {
        return this.response.url;
    }
    get data() {
        return this.response.data;
    }
    get revisedPrompt() {
        return this.response.revised_prompt;
    }
    get mimeType() {
        return this.response.mime_type;
    }
    get isBase64() {
        return !!this.data;
    }
    /**
     * Returns the raw binary image data as a Buffer.
     */
    async toBuffer() {
        if (this.data) {
            return Buffer.from(this.data, "base64");
        }
        if (this.url) {
            const resp = await fetch(this.url);
            if (!resp.ok) {
                throw new Error(`Failed to download image from ${this.url}: ${resp.statusText}`);
            }
            const arrayBuffer = await resp.arrayBuffer();
            return Buffer.from(arrayBuffer);
        }
        throw new Error("No image data or URL available");
    }
    /**
     * Returns a Readable stream of the image data.
     */
    async toStream() {
        const buffer = await this.toBuffer();
        return Readable.from(buffer);
    }
    /**
     * Saves the image to the specified local path.
     */
    async save(path) {
        const buffer = await this.toBuffer();
        await fs.writeFile(path, buffer);
        return path;
    }
    toString() {
        return this.valueOf();
    }
}
