import axios from 'axios';
import { NextResponse } from 'next/server';
import { geminiPrompt } from '../../../../lib/gemini';

const YT_KEY = process.env.YOUTUBE_API_KEY;
const BASE = 'https://www.googleapis.com/youtube/v3';

export async function POST(req: Request) {
    try {
        const body = await req.json();
        const { videoId, channelTitle, videoTitle } = body as {
            videoId: string;
            channelTitle: string;
            videoTitle: string;
        };

        if (!videoId) {
            return NextResponse.json({ error: 'Missing videoId' }, { status: 400 });
        }

        // 1. Fetch top 100 comments from YouTube
        const commentsRes = await axios.get(`${BASE}/commentThreads`, {
            params: {
                part: 'snippet',
                videoId,
                maxResults: 100,
                order: 'relevance',
                key: YT_KEY,
            },
        });

        const comments = (commentsRes.data.items || []).map((item: any) => {
            const c = item.snippet.topLevelComment.snippet;
            return {
                text: c.textDisplay,
                likes: c.likeCount || 0,
                author: c.authorDisplayName,
            };
        });

        if (comments.length === 0) {
            return NextResponse.json({ error: 'No comments found or comments are disabled for this video.' }, { status: 404 });
        }

        // Sort by likes to get highest engagement comments
        const topComments = comments.sort((a: any, b: any) => b.likes - a.likes).slice(0, 50);
        const commentText = topComments.map((c: any) => `[${c.likes} likes] ${c.text}`).join('\n');

        // 2. Send to Gemini for analysis
        const prompt = `You are a YouTube content strategist. Analyze the following comments from a YouTube video.

Channel: "${channelTitle}"
Video: "${videoTitle}"

Top ${topComments.length} comments (sorted by likes):
${commentText}

Respond with ONLY a valid JSON object (no markdown, no code blocks):
{
  "sentiment": "<one of: Very Positive | Positive | Neutral | Mixed | Negative>",
  "sentimentScore": <number 0-100, where 100 is most positive>,

  "painPoints": [
    "<specific pain point or frustration mentioned>",
    "<specific pain point or frustration mentioned>",
    "<specific pain point or frustration mentioned>"
  ],

  "commonQuestions": [
    "<exact question viewers are asking>",
    "<exact question viewers are asking>",
    "<exact question viewers are asking>"
  ],

  "videoIdeas": [
    { "title": "<specific video title idea>", "reason": "<why this would perform well>" },
    { "title": "<specific video title idea>", "reason": "<why this would perform well>" },
    { "title": "<specific video title idea>", "reason": "<why this would perform well>" },
    { "title": "<specific video title idea>", "reason": "<why this would perform well>" }
  ],

  "audienceProfile": "<2-3 sentences describing who is watching: their demographics, motivations, and level of expertise>",

  "topInsight": "<The single most actionable insight for a new creator entering this niche, based on what the audience is asking for>"
}`;

        const raw = await geminiPrompt(prompt);
        const jsonStr = raw.replace(/```json\n?/g, '').replace(/```\n?/g, '').trim();

        let analysis: Record<string, unknown>;
        try {
            analysis = JSON.parse(jsonStr);
        } catch {
            const match = jsonStr.match(/\{[\s\S]*\}/);
            analysis = match ? JSON.parse(match[0]) : { error: 'Failed to parse AI response' };
        }

        return NextResponse.json({
            videoId,
            videoTitle,
            commentCount: comments.length,
            ...analysis,
        });
    } catch (err: any) {
        const isDisabled = err?.response?.data?.error?.errors?.[0]?.reason === 'commentsDisabled';
        const msg = isDisabled ? 'Comments are disabled on this video.' : (err?.response?.data?.error?.message || err.message);
        console.error('Comments analyze error:', msg);
        return NextResponse.json({ error: msg }, { status: isDisabled ? 403 : 500 });
    }
}
