import { GoogleGenAI } from '@google/genai';
import type { StudioState } from '../types/studio';
import { CHANNEL_OPTIONS } from '../types/studio';

const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY ?? '' });

function buildPrompt(state: StudioState): string {
  const channel = CHANNEL_OPTIONS.find(c => c.channel === state.channel);
  const format = channel?.formats.find(f => f.key === state.format);

  const pillarDescriptions: Record<string, string> = {
    safety: 'hospital safety systems, clean surgical rooms, CCTV monitoring, professional medical team, trust and reliability',
    expertise: 'medical expertise, advanced surgical equipment, professional doctors, medical certifications, precision and skill',
    results: 'natural beautiful results, before and after transformation, patient satisfaction, subtle elegant outcomes',
    care: 'patient-centered care, warm consultation, personalized treatment plan, caring medical staff, comfortable clinic interior',
  };

  const pillarContext = state.pillarId ? pillarDescriptions[state.pillarId] ?? '' : '';
  const aspectRatio = format?.aspectRatio ?? '16:9';

  const channelHints: Record<string, string> = {
    youtube: 'YouTube thumbnail style, bold text overlay area, high contrast, eye-catching',
    instagram: 'Instagram aesthetic, clean minimalist, lifestyle photography style, warm tones',
    naver_blog: 'Korean blog header image, informative, medical illustration, clean layout',
    tiktok: 'TikTok cover image, vertical format, trendy, dynamic, youthful',
    facebook: 'Facebook ad creative, professional, compelling, clear messaging space',
  };

  const channelHint = state.channel ? channelHints[state.channel] ?? '' : '';

  return [
    'Generate a premium medical marketing image for a plastic surgery clinic.',
    `Theme: ${pillarContext}`,
    `Style: ${channelHint}`,
    `Aspect ratio: ${aspectRatio}`,
    'Color palette: soft purple (#7B2D8E), gold (#E8B931), warm white (#FAF8F5).',
    'Premium, luxurious, trustworthy aesthetic.',
    'No text or logos in the image.',
    'Photorealistic, high quality, professional medical marketing.',
  ].filter(Boolean).join(' ');
}

export interface GenerateResult {
  imageDataUrl: string;
  prompt: string;
}

export async function generateImage(state: StudioState): Promise<GenerateResult> {
  const prompt = buildPrompt(state);

  let response;
  try {
    response = await client.models.generateContent({
      model: 'gemini-2.5-flash-image',
      contents: prompt,
      config: {
        responseModalities: ['Text', 'Image'],
      },
    });
  } catch (err: any) {
    const code = err?.status ?? err?.code ?? err?.message?.match(/"code":(\d+)/)?.[1];
    if (String(code) === '429' || err?.message?.includes('RESOURCE_EXHAUSTED')) {
      throw new Error('API 요청 한도 초과 — 잠시 후 다시 시도해주세요');
    }
    if (String(code) === '400' || err?.message?.includes('INVALID_ARGUMENT')) {
      throw new Error('API 설정 오류 — 관리자에게 문의하세요');
    }
    throw new Error('이미지 생성 중 오류가 발생했습니다');
  }

  // Extract image from response parts
  const parts = response.candidates?.[0]?.content?.parts;
  if (!parts) throw new Error('AI 응답을 받지 못했습니다');

  const imagePart = parts.find((p: any) => p.inlineData?.mimeType?.startsWith('image/'));
  if (!imagePart?.inlineData) throw new Error('이미지가 생성되지 않았습니다 — 다시 시도해주세요');

  const { mimeType, data } = imagePart.inlineData;
  const imageDataUrl = `data:${mimeType};base64,${data}`;
  return { imageDataUrl, prompt };
}
