/**
 * AI Image Generator Service using Google Gemini API
 * Generates blog post cover images based on title and content
 */

import { GoogleGenAI } from '@google/genai';

// Validate API key
const apiKey = process.env.GOOGLE_CLOUD_API_KEY;

if (!apiKey) {
  console.warn('GOOGLE_CLOUD_API_KEY not set - AI image generation will be unavailable');
}

// Initialize Gemini client
const ai = apiKey ? new GoogleGenAI({ apiKey }) : null;

const MODEL_ID = 'gemini-3-pro-image-preview';

/**
 * Generation configuration for blog images
 */
const GENERATION_CONFIG = {
  maxOutputTokens: 32768,
  temperature: 1,
  topP: 0.95,
  responseModalities: ['TEXT', 'IMAGE'] as const,
  imageConfig: {
    aspectRatio: '16:9', // Blog cover image aspect ratio
    imageSize: '2K', // Higher quality for blog covers
    outputMimeType: 'image/png',
  },
  safetySettings: [
    {
      category: 'HARM_CATEGORY_HATE_SPEECH',
      threshold: 'OFF',
    },
    {
      category: 'HARM_CATEGORY_DANGEROUS_CONTENT',
      threshold: 'OFF',
    },
    {
      category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
      threshold: 'OFF',
    },
    {
      category: 'HARM_CATEGORY_HARASSMENT',
      threshold: 'OFF',
    },
  ],
};

export interface GenerateImageParams {
  title: string;
  excerpt?: string;
  tags?: string[];
  language?: 'ar' | 'en';
  existingPosts?: Array<{ title: string; coverImage?: string }>;
}

export interface GeneratedImage {
  base64: string;
  mimeType: string;
  prompt: string;
}

/**
 * Generate an AI image for a blog post using Gemini
 * Creates a contextual prompt based on the blog title, excerpt, and existing posts
 */
export async function generateBlogImage(
  params: GenerateImageParams
): Promise<GeneratedImage> {
  if (!ai) {
    throw new Error('AI image generation not configured - missing GOOGLE_CLOUD_API_KEY');
  }

  const { title, excerpt, tags = [], language = 'en', existingPosts = [] } = params;

  // Build contextual prompt
  const prompt = buildImagePrompt(title, excerpt, tags, language, existingPosts);

  try {
    const req = {
      model: MODEL_ID,
      contents: [
        {
          role: 'user',
          parts: [
            {
              text: prompt,
            },
          ],
        },
      ],
      config: GENERATION_CONFIG,
    };

    const streamingResp = await ai.models.generateContentStream(req);

    let imageData: string | null = null;
    let textResponse = '';

    // Process streaming response
    for await (const chunk of streamingResp) {
      if (chunk.text) {
        textResponse += chunk.text;
      }

      // Extract image data from response
      if (chunk.candidates && chunk.candidates[0]) {
        const candidate = chunk.candidates[0];
        if (candidate.content && candidate.content.parts) {
          for (const part of candidate.content.parts) {
            if (part.inlineData && part.inlineData.data) {
              imageData = part.inlineData.data;
              break;
            }
          }
        }
      }
    }

    if (!imageData) {
      throw new Error('No image data returned from Gemini API');
    }

    return {
      base64: imageData,
      mimeType: 'image/png',
      prompt,
    };
  } catch (error) {
    console.error('Error generating blog image:', error);
    throw new Error(
      `Failed to generate blog image: ${error instanceof Error ? error.message : 'Unknown error'}`
    );
  }
}

/**
 * Build a contextual prompt for image generation
 * Considers existing blog posts to maintain visual consistency
 */
function buildImagePrompt(
  title: string,
  excerpt: string | undefined,
  tags: string[],
  language: 'ar' | 'en',
  existingPosts: Array<{ title: string; coverImage?: string }>
): string {
  const isArabic = language === 'ar';

  // Base prompt
  let prompt = `Create a professional, modern blog cover image for a post titled "${title}".`;

  // Add excerpt context
  if (excerpt) {
    prompt += ` The post is about: ${excerpt}.`;
  }

  // Add tag context
  if (tags.length > 0) {
    prompt += ` Related topics: ${tags.join(', ')}.`;
  }

  // Style guidelines for Mawidi brand
  prompt += `\n\nStyle requirements:
- Professional and clean design suitable for a B2B SaaS platform
- Modern, tech-forward aesthetic
- Color palette: Emerald green (#10b981) as primary, with white and gray accents
- Avoid text in the image (text will be overlaid separately)
- High contrast and visually striking
- Suitable for both desktop and mobile viewing
- Related to appointment management, WhatsApp business, healthcare, or GCC region themes`;

  // Add language-specific context
  if (isArabic) {
    prompt += `\n- This is for an Arabic language blog post, consider Middle Eastern cultural context`;
  }

  // Add consistency guidance if there are existing posts
  if (existingPosts.length > 0) {
    const recentTitles = existingPosts.slice(0, 3).map((p) => p.title);
    prompt += `\n\nFor visual consistency with existing blog posts (recent titles: ${recentTitles.join(', ')}), maintain a cohesive design language while ensuring each image is unique.`;
  }

  prompt += `\n\nCreate an engaging, professional image that captures the essence of this topic.`;

  return prompt;
}

/**
 * Generate a simple fallback image prompt for testing
 */
export function generateSimplePrompt(title: string): string {
  return `Create a modern, professional blog cover image for: ${title}. Use emerald green color palette, clean design, no text.`;
}
