const fetch = require('node-fetch');

class ImageGenerator {
  constructor() {
    this.falKey = process.env.FAL_KEY;
    this.hfToken = process.env.HF_TOKEN;
    this.ideogramKey = process.env.IDEOGRAM_KEY;
  }

  async generate(provider, prompt, options = {}) {
    const {
      negativePrompt,
      aspectRatio = '9:16',
      model,
      seed,
      steps,
      cfg
    } = options;

    switch (provider) {
      case 'ideogram':
        return this._generateIdeogram(prompt, { aspectRatio });
      case 'fal':
        return this._generateFal(prompt, { aspectRatio, seed, steps, cfg });
      case 'hf':
      default:
        return this._generateHuggingFace(prompt, { negativePrompt });
    }
  }

  // Ideogram V2 (via Fal.ai) - Ottimo per testo
  async _generateIdeogram(prompt, options = {}) {
    console.log('--- Generazione Ideogram V2 ---');

    const response = await fetch('https://fal.run/fal-ai/ideogram/v2', {
      method: 'POST',
      headers: {
        Authorization: `Key ${this.falKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        prompt,
        aspect_ratio: options.aspectRatio || '9:16',
        style_type: 'DESIGN',
        expand_prompt: true
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`Ideogram error: ${response.status} - ${errorText}`);
    }

    const result = await response.json();
    const imageUrl = result.images?.[0]?.url;

    if (!imageUrl) throw new Error('Ideogram: nessun URL restituito');
    return imageUrl;
  }

  // Flux Dev (via Fal.ai)
  async _generateFal(prompt, options = {}) {
    console.log('--- Generazione Fal Flux Dev ---');

    const imageSizeMap = {
      '9:16': 'portrait_16_9',
      '16:9': 'landscape_16_9',
      '1:1': 'square'
    };

    const response = await fetch('https://fal.run/fal-ai/flux/dev', {
      method: 'POST',
      headers: {
        Authorization: `Key ${this.falKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        prompt,
        image_size: imageSizeMap[options.aspectRatio] || 'portrait_16_9',
        num_images: 1,
        enable_safety_checker: false,
        seed: options.seed,
        num_inference_steps: options.steps || 28,
        guidance_scale: options.cfg || 7.5
      }),
    });

    if (!response.ok) {
      throw new Error(`Fal error: ${response.status}`);
    }

    const result = await response.json();
    return result.images?.[0]?.url;
  }

  // Flux Dev (via Hugging Face) - GRATIS
  async _generateHuggingFace(prompt, options = {}) {
    console.log('--- Generazione HuggingFace (Gratis) ---');

    const response = await fetch(
      'https://router.huggingface.co/hf-inference/models/black-forest-labs/FLUX.1-dev',
      {
        headers: {
          Authorization: `Bearer ${this.hfToken}`,
          'Content-Type': 'application/json',
        },
        method: 'POST',
        body: JSON.stringify({
          inputs: prompt,
          parameters: {
            negative_prompt: options.negativePrompt
          }
        }),
      }
    );

    if (!response.ok) {
      const err = await response.text();
      throw new Error(`HuggingFace error: ${response.status} - ${err}`);
    }

    const arrayBuffer = await response.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);
    return `data:image/jpeg;base64,${buffer.toString('base64')}`;
  }

  // Utility: verifica disponibilità provider
  async checkProvider(provider) {
    const checks = {
      hf: !!this.hfToken,
      fal: !!this.falKey,
      ideogram: !!this.falKey // Ideogram via Fal
    };

    return checks[provider] || false;
  }

  // Lista provider disponibili
  getAvailableProviders() {
    const providers = [];

    if (this.hfToken) {
      providers.push({ id: 'hf', name: 'HuggingFace (Gratis)', cost: 'free' });
    }
    if (this.falKey) {
      providers.push({ id: 'fal', name: 'Fal Flux Dev', cost: 'paid' });
      providers.push({ id: 'ideogram', name: 'Ideogram V2', cost: 'paid' });
    }

    return providers;
  }
}

module.exports = new ImageGenerator();