import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { hybridAI } from '@/lib/ai/hybridRouter';

export async function POST(request: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user }, error: authError } = await supabase.auth.getUser();
    if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const { title, content, siteId } = await request.json();

    const text = `${title}\n\n${(content || '').slice(0, 2000)}`;

    try {
      const result = await hybridAI(
        [
          {
            role: 'system',
            content: `You are a content classifier for two broadcast and AV industry publications. Given a post title and body, determine if it is: (1) Broadcast/TV/Film/Radio/Post Production content, (2) Professional AV Integration content, or (3) Could fit either. Return JSON only: {"scope":"broadcast"|"av"|"either","confidence":0-1}`,
          },
          { role: 'user', content: text },
        ],
        { maxTokens: 200, isBackground: false, priority: 6 }
      );

      const match = result.text.match(/\{[\s\S]*?\}/);
      if (match) {
        const parsed = JSON.parse(match[0]);
        return NextResponse.json({ scope: parsed.scope || 'either', confidence: parsed.confidence || 0 });
      }
    } catch {
      // fall through to default
    }

    return NextResponse.json({ scope: 'either', confidence: 0 });
  } catch {
    return NextResponse.json({ scope: 'either', confidence: 0 });
  }
}
