import { NextRequest, NextResponse } from 'next/server';
import { getChatCompletion } from '@/lib/ai/chatCompletion';

interface ModerationResult {
  flagged: boolean;
  reason: string | null;
  categories: {
    spam: boolean;
    profanity: boolean;
    off_topic: boolean;
  };
  confidence: 'low' | 'medium' | 'high';
}

const MODERATION_SYSTEM_PROMPT = `You are a content moderation assistant for a broadcast media community forum. Your job is to analyze forum content and detect:

1. SPAM: Repetitive content, promotional links, gibberish, bot-like patterns, excessive self-promotion
2. PROFANITY: Offensive language, hate speech, slurs, explicit sexual content, severe insults
3. OFF_TOPIC: Content completely unrelated to media, broadcasting, journalism, entertainment, or community discussion

You must respond with ONLY a valid JSON object in this exact format:
{
  "flagged": true or false,
  "reason": "Brief explanation if flagged, null if clean",
  "categories": {
    "spam": true or false,
    "profanity": true or false,
    "off_topic": true or false
  },
  "confidence": "low" or "medium" or "high"
}

Be conservative — only flag content that clearly violates these rules. Do not flag borderline cases or content that is merely controversial or opinionated.`;

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { content_type, title, body: contentBody, category_name } = body;

    if (!contentBody) {
      return NextResponse.json({ error: 'content body is required' }, { status: 400 });
    }

    // Build the user message for Claude
    let userMessage = '';
    if (content_type === 'thread') {
      userMessage = `Analyze this forum thread for spam, profanity, or off-topic content.

Thread Title: ${title || '(no title)'}
Category: ${category_name || 'General'}
Thread Body:
${contentBody}`;
    } else {
      userMessage = `Analyze this forum reply for spam, profanity, or off-topic content.

Reply Body:
${contentBody}`;
    }

    const response = await getChatCompletion(
      'ANTHROPIC',
      'claude-haiku-4-5-20251001',
      [
        { role: 'system', content: MODERATION_SYSTEM_PROMPT },
        { role: 'user', content: userMessage },
      ],
      {
        temperature: 0.1,
        max_tokens: 256,
      }
    );

    // Extract the text content from the response
    const rawText: string = response?.choices?.[0]?.message?.content || '';

    let result: ModerationResult;
    try {
      // Strip markdown code fences if present
      const cleaned = rawText.replace(/```json\s*/gi, '').replace(/```\s*/gi, '').trim();
      result = JSON.parse(cleaned);
    } catch {
      // If Claude returns unexpected format, default to not flagged
      result = {
        flagged: false,
        reason: null,
        categories: { spam: false, profanity: false, off_topic: false },
        confidence: 'low',
      };
    }

    return NextResponse.json({ moderation: result });
  } catch (err: any) {
    // On AI error, return safe default (don't block content creation)
    return NextResponse.json({
      moderation: {
        flagged: false,
        reason: null,
        categories: { spam: false, profanity: false, off_topic: false },
        confidence: 'low',
      },
      ai_error: err.message,
    });
  }
}
