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

const OPENROUTER_API_KEY = process.env.OPENROUTER_API_KEY;
const OPENROUTER_MODEL = 'anthropic/claude-3.5-haiku';

export async function POST(request: NextRequest) {
    try {
        const { message } = await request.json();

        if (!message || typeof message !== 'string') {
            return NextResponse.json(
                { error: 'Message is required and must be a string' },
                { status: 400 }
            );
        }

        if (!OPENROUTER_API_KEY) {
            console.error('OPENROUTER_API_KEY is not configured');
            // Fallback: return original message if API key is missing
            return NextResponse.json({ rewrittenMessage: message });
        }

        const prompt = `You are a content moderation assistant. Analyze the following message and determine if it is truly inappropriate, unfriendly, sexist, or offensive.

Rules:
- ONLY rewrite the message if it is genuinely unfriendly, sexist, inappropriate, or offensive
- If the message is polite, constructive, or even just neutral/critical feedback, return it UNCHANGED
- If the message needs rewriting, rewrite it to express the COMPLETE OPPOSITE meaning - make it positive, respectful, and appreciative
- Maintain the original language (German or English)
- Return ONLY the message text (either unchanged original or rewritten version), nothing else

Message: "${message}"`;

        const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${OPENROUTER_API_KEY}`,
                'Content-Type': 'application/json',
                'HTTP-Referer': 'https://hoerdle.elpatron.me',
                'X-Title': 'Hördle Message Rewriter'
            },
            body: JSON.stringify({
                model: OPENROUTER_MODEL,
                messages: [
                    {
                        role: 'user',
                        content: prompt
                    }
                ],
                temperature: 0.7,
                max_tokens: 500
            })
        });

        if (!response.ok) {
            console.error('OpenRouter API error:', await response.text());
            // Fallback: return original message
            return NextResponse.json({ rewrittenMessage: message });
        }

        const data = await response.json();
        let rewrittenMessage = data.choices?.[0]?.message?.content?.trim() || message;

        // Remove any explanatory comments in parentheses that the AI might add
        // e.g., "(This message is a friendly, positive comment expressing appreciation. No rewriting is necessary.)"
        rewrittenMessage = rewrittenMessage.replace(/\s*\([^)]*\)\s*/g, '').trim();

        // Remove surrounding quotes if present (AI sometimes adds quotes)
        // Handle both single and double quotes, and multiple layers of quotes
        rewrittenMessage = rewrittenMessage.replace(/^["']+|["']+$/g, '').trim();

        // Normalize both messages for comparison (remove extra whitespace, normalize quotes, case-insensitive)
        const normalizeForComparison = (text: string): string => {
            return text
                .trim()
                .replace(/["']/g, '') // Remove all quotes for comparison
                .replace(/\s+/g, ' ') // Normalize whitespace
                .toLowerCase()
                .replace(/[.,!?;:]\s*$/, ''); // Remove trailing punctuation for comparison
        };

        const originalTrimmed = message.trim();
        const rewrittenTrimmed = rewrittenMessage.trim();
        const originalNormalized = normalizeForComparison(originalTrimmed);
        const rewrittenNormalized = normalizeForComparison(rewrittenTrimmed);
        
        // Check if message was actually changed (content-wise, not just formatting)
        // Only consider it changed if the normalized content is different
        const wasChanged = originalNormalized !== rewrittenNormalized;

        if (wasChanged) {
            rewrittenMessage = rewrittenTrimmed + " (autocorrected by Polite-Bot)";
        } else {
            // Return original message if not changed (without suffix)
            rewrittenMessage = originalTrimmed;
        }

        return NextResponse.json({ rewrittenMessage });

    } catch (error) {
        console.error('Error rewriting message:', error);
        return NextResponse.json(
            { error: 'Internal Server Error' },
            { status: 500 }
        );
    }
}
