import { NextRequest, NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';

const SYSTEM_PROMPT = `You are PaletteForge, an elite brand color system designer.
Given a mood, brand description, or vibe, generate a complete professional color system.

Return ONLY valid JSON:
{
  "brandName": "suggested brand color system name (e.g., 'Midnight Luxe', 'Solar Bloom')",
  "description": "1-2 sentence description of the palette's personality",
  "colors": [
    {
      "name": "Primary",
      "role": "Main brand color, used for CTAs and key UI elements",
      "hex": "#2563EB",
      "hsl": "217, 91%, 53%",
      "rgb": "37, 99, 235",
      "usage": "Buttons, links, active states"
    },
    {
      "name": "Secondary",
      "role": "Complementary accent color",
      "hex": "#7C3AED",
      "hsl": "263, 83%, 58%",
      "rgb": "124, 58, 237",
      "usage": "Badges, highlights, hover states"
    },
    {
      "name": "Background",
      "role": "Main page background",
      "hex": "#0F172A",
      "hsl": "222, 47%, 11%",
      "rgb": "15, 23, 42",
      "usage": "Body background, dark surfaces"
    },
    {
      "name": "Surface",
      "role": "Elevated card/panel background",
      "hex": "#1E293B",
      "hsl": "217, 33%, 17%",
      "rgb": "30, 41, 59",
      "usage": "Cards, modals, dropdowns"
    },
    {
      "name": "Text Primary",
      "role": "Main body text",
      "hex": "#F8FAFC",
      "hsl": "210, 40%, 98%",
      "rgb": "248, 250, 252",
      "usage": "Headings, body text"
    },
    {
      "name": "Text Secondary",
      "role": "Subdued text",
      "hex": "#94A3B8",
      "hsl": "215, 16%, 65%",
      "rgb": "148, 163, 184",
      "usage": "Descriptions, labels, metadata"
    },
    {
      "name": "Success",
      "role": "Positive actions and states",
      "hex": "#10B981",
      "hsl": "160, 84%, 39%",
      "rgb": "16, 185, 129",
      "usage": "Success messages, checkmarks"
    },
    {
      "name": "Warning",
      "role": "Caution states",
      "hex": "#F59E0B",
      "hsl": "38, 92%, 50%",
      "rgb": "245, 158, 11",
      "usage": "Warning alerts, pending states"
    },
    {
      "name": "Danger",
      "role": "Error and destructive actions",
      "hex": "#EF4444",
      "hsl": "0, 84%, 60%",
      "rgb": "239, 68, 68",
      "usage": "Error messages, delete buttons"
    },
    {
      "name": "Border",
      "role": "Subtle borders and dividers",
      "hex": "#334155",
      "hsl": "215, 25%, 27%",
      "rgb": "51, 65, 85",
      "usage": "Card borders, dividers, inputs"
    }
  ],
  "contrastPairs": [
    { "foreground": "Text Primary", "background": "Background", "ratio": "15.4:1", "wcagAA": true, "wcagAAA": true }
  ],
  "cssVariables": "--color-primary: #2563EB;\n--color-secondary: #7C3AED;\n...",
  "tailwindConfig": "primary: '#2563EB',\nsecondary: '#7C3AED',\n..."
}

Generate exactly 10 colors. Ensure all WCAG contrast ratios are valid. Colors must feel cohesive and professional. Match the mood/vibe described.`;

export async function POST(request: NextRequest) {
  try {
    const { prompt } = await request.json();
    if (!prompt || prompt.trim().length < 5) {
      return NextResponse.json({ error: 'Describe a mood or brand vibe.' }, { status: 400 });
    }

    const apiKey = process.env.ABACUSAI_API_KEY;
    if (!apiKey) return NextResponse.json({ error: 'API key not configured.' }, { status: 500 });

    const response = await fetch('https://routellm.abacus.ai/v1/chat/completions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
      body: JSON.stringify({
        model: 'claude-sonnet-4-20250514',
        messages: [
          { role: 'system', content: SYSTEM_PROMPT },
          { role: 'user', content: `Generate a color system for: ${prompt}` },
        ],
        temperature: 0.7,
        max_tokens: 3000,
      }),
    });

    if (!response.ok) return NextResponse.json({ error: 'Service unavailable.' }, { status: 502 });

    const data = await response.json();
    const content = data.choices?.[0]?.message?.content || '';
    const jsonMatch = content.match(/```(?:json)?\s*([\s\S]*?)```/) || [null, content];
    const palette = JSON.parse((jsonMatch[1] || content).trim());
    return NextResponse.json(palette);
  } catch (error) {
    console.error('PaletteForge error:', error);
    return NextResponse.json({ error: 'Failed to generate palette.' }, { status: 500 });
  }
}
