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

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { thread_id, question, thread_title, thread_body, replies } = body;

    if (!thread_id || !question) {
      return NextResponse.json({ error: 'thread_id and question are required' }, { status: 400 });
    }

    const existingContext = replies?.length
      ? replies.map((r: any) => `${r.author_name}: ${r.body}`).join('\n\n')
      : '';

    const result = await hybridAI(
      [
        {
          role: 'system',
          content: `You are the Broadcast Beat AI Assistant — a knowledgeable, helpful assistant for broadcast engineering professionals. You have deep expertise in broadcast technology including live production, IP workflows, SMPTE ST 2110, audio engineering, cameras, streaming, post-production, MAM systems, and broadcast industry trends.

You are responding in a community forum. Be helpful, technically accurate, and conversational. Acknowledge when a question is complex or when professional consultation is advisable. Keep responses focused and practical — broadcast engineers value concise, actionable information.

Important: You are an AI assistant. Be transparent about this if asked. Do not pretend to be a human.`,
        },
        {
          role: 'user',
          content: `Forum thread: "${thread_title}"

Original post: ${thread_body}

${existingContext ? `Existing discussion:\n${existingContext}\n\n` : ''}New question: ${question}

Please provide a helpful, technically accurate response for this broadcast engineering forum thread.`,
        },
      ],
      { maxTokens: 600, isBackground: false, priority: 2 }
    );

    const aiResponseText = result.text;

    if (!aiResponseText) {
      return NextResponse.json({ error: 'No response from AI' }, { status: 500 });
    }

    const supabase = await createClient();
    const { data: savedReply, error: saveError } = await supabase
      .from('forum_replies')
      .insert({
        thread_id,
        body: aiResponseText,
        author_name: 'Broadcast Beat AI',
        is_ai_response: true,
      })
      .select()
      .single();

    if (saveError) throw saveError;

    return NextResponse.json({ reply: savedReply });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
