"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImageProviderManager = void 0;
exports.getImageProvider = getImageProvider;
exports.refreshImageProvider = refreshImageProvider;
const logger_js_1 = require("../../utils/logger.js");
const config_js_1 = require("../../utils/config.js");
const kie_client_js_1 = require("./kie-client.js");
const gemini_client_js_1 = require("./gemini-client.js");
const logger = (0, logger_js_1.createModuleLogger)('image-provider');
/**
 * Unified image generation provider.
 * Priority: Gemini (primary) → KIE (fallback).
 */
class ImageProviderManager {
    kieClient = null;
    geminiClient = null;
    constructor() {
        this.refresh();
    }
    /** Re-read config and recreate clients (call after API key update). */
    refresh() {
        this.kieClient = config_js_1.config.kieApiKey ? (0, kie_client_js_1.createKIEClient)() : null;
        this.geminiClient = config_js_1.config.geminiApiKey ? (0, gemini_client_js_1.createGeminiClient)(config_js_1.config.geminiApiKey) : null;
        const providers = [];
        if (this.geminiClient)
            providers.push('Gemini');
        if (this.kieClient)
            providers.push('KIE');
        logger.info({ providers, primary: this.getPrimaryProvider() }, 'Image providers initialized');
    }
    /** Returns which provider will be used as primary. */
    getPrimaryProvider() {
        if (this.geminiClient)
            return 'gemini';
        if (this.kieClient)
            return 'kie';
        return null;
    }
    /** Returns true if at least one image provider is available. */
    isAvailable() {
        return !!(this.geminiClient || this.kieClient);
    }
    /** Get the raw KIE client. */
    getKIEClient() {
        return this.kieClient;
    }
    /** Get the raw Gemini client. */
    getGeminiClient() {
        return this.geminiClient;
    }
    /**
     * Generate an image. Gemini first, KIE fallback.
     * Uses generateAndWait (synchronous polling).
     */
    async generateAndWait(request) {
        // Try Gemini first (primary)
        if (this.geminiClient) {
            try {
                logger.info({ prompt: request.prompt.slice(0, 60) }, 'Generating with Gemini (primary)');
                return await this.generateWithGemini(request);
            }
            catch (geminiError) {
                logger.warn({ error: geminiError.message }, 'Gemini image generation failed');
                // Fall back to KIE
                if (this.kieClient) {
                    logger.info({}, 'Falling back to KIE');
                    const imageUrl = await this.kieClient.generateAndWait(request);
                    return { imageUrl, provider: 'kie' };
                }
                throw geminiError;
            }
        }
        // Gemini not available, try KIE
        if (this.kieClient) {
            logger.info({}, 'Gemini not configured, using KIE');
            const imageUrl = await this.kieClient.generateAndWait(request);
            return { imageUrl, provider: 'kie' };
        }
        throw new Error('Görsel üretim servisi yapılandırılmamış. Gemini veya KIE API anahtarı gerekli.');
    }
    async generateWithGemini(request) {
        if (!this.geminiClient) {
            throw new Error('Gemini API anahtarı yapılandırılmamış');
        }
        // Collect reference image URLs from request fields
        const refUrls = request.imageInput ?? request.referenceImages ?? request.inputUrls ?? [];
        const imageUrl = await this.geminiClient.generateFromKIERequest({
            prompt: request.prompt,
            aspectRatio: request.aspectRatio,
            referenceImageUrls: refUrls.length > 0 ? refUrls : undefined,
        });
        return { imageUrl, provider: 'gemini' };
    }
}
exports.ImageProviderManager = ImageProviderManager;
let _instance = null;
function getImageProvider() {
    if (!_instance) {
        _instance = new ImageProviderManager();
    }
    return _instance;
}
function refreshImageProvider() {
    if (_instance) {
        _instance.refresh();
    }
}
//# sourceMappingURL=image-provider.js.map