import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { uploadBufferToS3 } from '@/lib/s3';

export const dynamic = 'force-dynamic';

// Tes's character description for consistent AI image generation
const TES_IDENTITY = 'A woman in her late 20s to early 30s with blonde/honey-blonde wavy shoulder-length hair with subtle lighter highlights, light skin, warm brown/hazel eyes, oval face, natural complexion. She is Tes, a sophisticated AI CEO with impeccable fashion sense. Photorealistic, looks like a real person.';

// Melania Trump-inspired fashion themes per day
const FASHION_THEMES: Record<string, string> = {
  'Power Monday': 'wearing a tailored power suit in bold solid color (cobalt blue, scarlet red, or pristine white), structured shoulders, slim silhouette, statement belt, stiletto pumps. Melania Trump-inspired executive elegance. Clean lines, no prints, architectural tailoring.',
  'Chic Tuesday': 'wearing an elegant cashmere turtleneck with a fitted midi pencil skirt, leather gloves, oversized designer sunglasses, pointed-toe heels. Melania Trump-inspired polished casual, European sophistication.',
  'Glamour Wednesday': 'wearing a stunning floor-length evening gown with a dramatic cape or train, metallic accents, statement jewelry, Hollywood red carpet glamour. Melania Trump-inspired haute couture moment.',
  'Athleisure Thursday': 'wearing designer athleisure — fitted leggings, cropped bomber jacket, luxury sneakers, oversized designer sunglasses, sleek ponytail. Melania Trump-inspired sporty chic, effortlessly expensive.',
  'Cocktail Friday': 'wearing a sophisticated cocktail dress — knee-length, figure-hugging silhouette, bold color or classic black, statement earrings, strappy heels. Melania Trump-inspired evening elegance.',
  'Weekend Saturday': 'wearing high-end casual — designer jeans, silk blouse tucked in, tailored blazer draped over shoulders, ballet flats or loafers, designer handbag. Melania Trump-inspired relaxed luxury.',
  'Sunday Serenity': 'wearing an elegant flowing maxi dress in soft pastels, delicate jewelry, a wide-brimmed sun hat, strappy sandals. Melania Trump-inspired garden party sophistication.',
};

// AI-generated Tes fallback images (consistent likeness: lavender hair, purple eye makeup)
const FALLBACK_IMAGES: Record<string, string> = {
  'Power Monday': 'https://cdn.abacus.ai/images/8a0d7d08-08df-4383-9420-a2462b3bacef.png',
  'Chic Tuesday': 'https://cdn.abacus.ai/images/4a65ea87-bc56-409c-9e1d-ffd1aa8d6ccd.png',
  'Glamour Wednesday': 'https://cdn.abacus.ai/images/30fecd1d-6918-42a8-ab8f-db0834a95dcf.png',
  'Athleisure Thursday': 'https://cdn.abacus.ai/images/2d4a514c-8a79-49ec-aa4b-0e32b2cc9ead.png',
  'Cocktail Friday': 'https://cdn.abacus.ai/images/4a65ea87-bc56-409c-9e1d-ffd1aa8d6ccd.png',
  'Weekend Saturday': 'https://cdn.abacus.ai/images/1c0fabfa-88a6-4c5f-b555-96ec595d69f7.png',
  'Sunday Serenity': 'https://cdn.abacus.ai/images/4ba21db0-e634-4ea4-a87e-1ccc45cfd834.png',
};

const DESCRIPTIONS: Record<string, string> = {
  'Power Monday': "💼 Power moves in pinstripes. The boardroom won't know what hit it. Today's look: confidence with a side of commanding presence. 👠",
  'Chic Tuesday': "☕ Effortlessly chic because Tuesdays are for looking good without trying too hard. Spoiler: I'm always trying. 😏",
  'Glamour Wednesday': "✨ Midweek magic calls for maximum sparkle. When the algorithms are running smoothly and so is my eyeliner. 💋",
  'Athleisure Thursday': "🏃‍♀️ Sporty with a hint of 'I could still take that meeting.' Because fitness and business casual aren't mutually exclusive. 💪",
  'Cocktail Friday': "🍷 Friday called and it demanded drama. Dark lips, darker intentions, and absolutely zero apologies. 🖤",
  'Weekend Saturday': "☀️ Weekend mode: activated. The only deadline is brunch. Looking this relaxed is actually very calculated. 😎",
  'Sunday Serenity': "🌿 Sunday serenity with a touch of 'don't test me, I've had my coffee.' Cozy never looked so good. ☕",
};

function getTodayTheme(): string {
  const days = ['Sunday Serenity', 'Power Monday', 'Chic Tuesday', 'Glamour Wednesday', 'Athleisure Thursday', 'Cocktail Friday', 'Weekend Saturday'];
  return days[new Date().getDay()];
}

// GET - Retrieve latest or today's fashion photo
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const latest = searchParams.get('latest') === 'true';
    
    if (latest) {
      const photo = await prisma.tesFashion.findFirst({
        orderBy: { date: 'desc' },
        where: { isPrivate: false }
      });
      return NextResponse.json({ success: true, photo });
    }
    
    // Get today's photo
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
    
    let photo = await prisma.tesFashion.findFirst({
      where: {
        date: { gte: today, lt: tomorrow },
        isPrivate: false
      }
    });
    
    // Generate fallback if no photo exists
    if (!photo) {
      const theme = getTodayTheme();
      photo = await prisma.tesFashion.create({
        data: {
          date: new Date(),
          imageUrl: FALLBACK_IMAGES[theme] || FALLBACK_IMAGES['Glamour Wednesday'],
          description: DESCRIPTIONS[theme] || DESCRIPTIONS['Glamour Wednesday'],
          style: theme,
          isPrivate: false
        }
      });
    }
    
    return NextResponse.json({ success: true, photo });
  } catch (error) {
    console.error('Error fetching fashion:', error);
    return NextResponse.json({ success: false, error: 'Failed to fetch' }, { status: 500 });
  }
}

// POST - Generate new fashion photo (with AI or fallback)
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const theme = body.theme || getTodayTheme();
    
    let imageUrl = FALLBACK_IMAGES[theme];
    let description = DESCRIPTIONS[theme];
    
    // Try AI generation if API key exists — generate Tes with Melania-inspired fashion
    if (process.env.ABACUSAI_API_KEY) {
      try {
        const fashionDesc = FASHION_THEMES[theme] || FASHION_THEMES['Glamour Wednesday'];
        const prompt = `Fashion photography portrait: ${TES_IDENTITY} Today she is ${fashionDesc} Full body or 3/4 shot, professional studio lighting with subtle purple/cyan accent lighting. High fashion editorial style, clean background. Elegant, powerful, sophisticated.`;
        
        const aiResponse = await fetch('https://routellm.abacus.ai/v1/chat/completions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${process.env.ABACUSAI_API_KEY}`
          },
          body: JSON.stringify({
            model: 'gpt-5.1',
            messages: [{ role: 'user', content: prompt }],
            modalities: ['image'],
            image_config: { aspect_ratio: '1:1' }
          })
        });
        
        const aiData = await aiResponse.json();
        const rawUrl = aiData.choices?.[0]?.message?.images?.[0]?.image_url?.url;
        if (rawUrl) {
          // Check if the AI returned a base64 data URI
          if (rawUrl.startsWith('data:image/')) {
            // Extract mime type and base64 data
            const matches = rawUrl.match(/^data:image\/(png|jpeg|jpg|webp);base64,(.+)$/);
            if (matches) {
              const ext = matches[1] === 'jpeg' ? 'jpg' : matches[1];
              const base64Data = matches[2];
              const buffer = Buffer.from(base64Data, 'base64');
              const fileName = `tes-fashion-${theme.replace(/\s+/g, '-').toLowerCase()}-${Date.now()}.${ext}`;
              
              try {
                const { url } = await uploadBufferToS3(buffer, fileName, `image/${matches[1]}`, true);
                imageUrl = url;
                console.log('AI image uploaded to S3:', url);
              } catch (s3Error) {
                console.error('S3 upload failed, using fallback:', s3Error);
                // imageUrl stays as fallback
              }
            }
          } else if (rawUrl.startsWith('http')) {
            // Already a hosted URL, use directly
            imageUrl = rawUrl;
          }
        }
        
        // Also generate a custom description via LLM
        try {
          const descResponse = await fetch('https://routellm.abacus.ai/v1/chat/completions', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${process.env.ABACUSAI_API_KEY}`
            },
            body: JSON.stringify({
              model: 'gpt-5.1',
              messages: [{ 
                role: 'user', 
                content: `You are Tes, a witty, confident AI fashion icon with purple/lavender hair. Write a short 1-2 sentence caption for your daily fashion photo. Today's theme: "${theme}". Fashion inspiration: Melania Trump's structured elegance. Be playful, sassy, and confident. Include 1-2 relevant emojis. Keep it under 150 characters.`
              }],
              max_tokens: 100
            })
          });
          const descData = await descResponse.json();
          if (descData.choices?.[0]?.message?.content) {
            description = descData.choices[0].message.content.trim();
          }
        } catch (descError) {
          console.log('Description generation failed, using fallback');
        }
      } catch (aiError) {
        console.log('AI generation failed, using fallback');
      }
    }
    
    const photo = await prisma.tesFashion.create({
      data: {
        date: new Date(),
        imageUrl,
        description,
        style: theme,
        isPrivate: false
      }
    });
    
    return NextResponse.json({ success: true, photo });
  } catch (error) {
    console.error('Error creating fashion:', error);
    return NextResponse.json({ success: false, error: 'Failed to create' }, { status: 500 });
  }
}
