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

export const dynamic = 'force-dynamic';

const SYSTEM_PROMPT = `You are BirthdayBrief, a friendly astrology advisor who speaks in plain, modern English — NO mystical language, no "celestial bodies" or "cosmic energy" or "the universe has aligned." Talk like a smart friend giving real advice over coffee.

Given a zodiac sign and today's date, provide:
1. dailyAdvice: 3-4 sentences of genuinely useful life/career/relationship advice for today. Be specific and practical. Reference current events, seasonal activities, or real-world situations. Never say "stars" or "planets" or "universe."
2. luckyNumber: a number 1-99
3. mood: one word describing today's vibe
4. focusArea: "career" | "relationships" | "health" | "creativity" | "finances" | "personal-growth"
5. compatibility: which sign vibes best with them today and why (1 sentence, casual)
6. doToday: one specific, actionable thing to do today (e.g., "Text that friend you've been meaning to catch up with")
7. avoidToday: one thing to skip today (e.g., "Don't make any big purchases on impulse")

Respond ONLY with valid JSON:
{
  "dailyAdvice": "...",
  "luckyNumber": 42,
  "mood": "focused",
  "focusArea": "career",
  "compatibility": "...",
  "doToday": "...",
  "avoidToday": "..."
}`;

const ZODIAC_SIGNS = [
  { sign: 'Capricorn', dates: 'Dec 22 - Jan 19', emoji: '\u2651' },
  { sign: 'Aquarius', dates: 'Jan 20 - Feb 18', emoji: '\u2652' },
  { sign: 'Pisces', dates: 'Feb 19 - Mar 20', emoji: '\u2653' },
  { sign: 'Aries', dates: 'Mar 21 - Apr 19', emoji: '\u2648' },
  { sign: 'Taurus', dates: 'Apr 20 - May 20', emoji: '\u2649' },
  { sign: 'Gemini', dates: 'May 21 - Jun 20', emoji: '\u264a' },
  { sign: 'Cancer', dates: 'Jun 21 - Jul 22', emoji: '\u264b' },
  { sign: 'Leo', dates: 'Jul 23 - Aug 22', emoji: '\u264c' },
  { sign: 'Virgo', dates: 'Aug 23 - Sep 22', emoji: '\u264d' },
  { sign: 'Libra', dates: 'Sep 23 - Oct 22', emoji: '\u264e' },
  { sign: 'Scorpio', dates: 'Oct 23 - Nov 21', emoji: '\u264f' },
  { sign: 'Sagittarius', dates: 'Nov 22 - Dec 21', emoji: '\u2650' },
];

function getZodiacSign(month: number, day: number): typeof ZODIAC_SIGNS[0] | null {
  const idx = [
    [1,19,0],[1,20,1],[2,18,1],[2,19,2],[3,20,2],[3,21,3],[4,19,3],[4,20,4],
    [5,20,4],[5,21,5],[6,20,5],[6,21,6],[7,22,6],[7,23,7],[8,22,7],[8,23,8],
    [9,22,8],[9,23,9],[10,22,9],[10,23,10],[11,21,10],[11,22,11],[12,21,11],[12,22,0]
  ];
  for (let i = 0; i < idx.length; i += 2) {
    if (month === idx[i][0] && day <= idx[i][1]) return ZODIAC_SIGNS[idx[i][2]];
    if (month === idx[i+1][0] && day >= idx[i+1][1]) return ZODIAC_SIGNS[idx[i+1][2]];
  }
  return ZODIAC_SIGNS[0];
}

export async function POST(request: NextRequest) {
  try {
    const { month, day } = await request.json();
    if (!month || !day) return NextResponse.json({ error: 'Month and day required.' }, { status: 400 });

    const zodiac = getZodiacSign(month, day);
    if (!zodiac) return NextResponse.json({ error: 'Invalid date.' }, { status: 400 });

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

    const today = new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' });

    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: `Sign: ${zodiac.sign}. Today is ${today}. Give the daily brief.` },
        ],
        temperature: 0.8,
        max_tokens: 1000,
      }),
    });

    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 brief = JSON.parse((jsonMatch[1] || content).trim());

    return NextResponse.json({ ...brief, sign: zodiac.sign, emoji: zodiac.emoji, dates: zodiac.dates });
  } catch (error) {
    console.error('BirthdayBrief error:', error);
    return NextResponse.json({ error: 'Failed to generate brief.' }, { status: 500 });
  }
}
