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

// Trend Persistence Score: pure data computation (no AI needed)
// Measures how well a channel sustained momentum after its viral peak
function computeTrendPersistence(videos: {
    id: string;
    title: string;
    views: number;
    publishedAt: string;
    isOutperformer: boolean;
    outperformRatio: number;
}[], avgViewsPerVideo: number) {
    // Find the top outperformer
    const sorted = [...videos].sort((a, b) => b.views - a.views);
    const topViral = sorted[0];
    if (!topViral || avgViewsPerVideo === 0) {
        return { score: 0, label: 'Unknown', rationale: 'Insufficient data', followUpRatio: 0 };
    }

    // Sort by date and find where the viral video sits
    const byDate = [...videos].sort((a, b) => new Date(a.publishedAt).getTime() - new Date(b.publishedAt).getTime());
    const viralIdx = byDate.findIndex(v => v.id === topViral.id);

    // Get 1–3 videos published AFTER the viral one
    const followUps = byDate.slice(viralIdx + 1, viralIdx + 4);
    const followUpAvg = followUps.length > 0
        ? followUps.reduce((s, v) => s + v.views, 0) / followUps.length
        : 0;

    const followUpRatio = avgViewsPerVideo > 0 ? parseFloat((followUpAvg / avgViewsPerVideo).toFixed(2)) : 0;

    // Outperformer count overall
    const outperformerPct = parseFloat(((videos.filter(v => v.isOutperformer).length / videos.length) * 100).toFixed(1));

    let score: number, label: string, rationale: string;

    if (followUpRatio >= 2 && outperformerPct >= 20) {
        score = 90; label = '🔥 Durable Breakout'; rationale = `Follow-up videos averaged ${followUpRatio}× the channel mean — format and audience locked in.`;
    } else if (followUpRatio >= 1.5 || outperformerPct >= 15) {
        score = 70; label = '✅ Building Momentum'; rationale = `Follow-ups performed ${followUpRatio}× average — channel is finding its footing.`;
    } else if (followUpRatio >= 1 || outperformerPct >= 8) {
        score = 50; label = '🟡 Mixed Signals'; rationale = `Only modest follow-up performance (${followUpRatio}× avg). Could be early or one-off.`;
    } else {
        score = 25; label = '⚡ Flash Spike'; rationale = `Follow-ups dropped back to baseline (${followUpRatio}× avg). Likely algorithmic test, not format breakout.`;
    }

    return { score, label, rationale, followUpRatio, followUpCount: followUps.length, outperformerPct };
}

// Risk Flags: heuristic-based, no AI needed
function computeRiskFlags(videos: { title: string; views: number; duration: number; isShort: boolean }[], channelDescription: string) {
    const flags: { type: string; severity: 'High' | 'Medium' | 'Low'; detail: string }[] = [];

    // Reused content / compilation indicator: very similar titles
    const titles = videos.map(v => v.title.toLowerCase());
    const commonPrefixes = ['top 10', 'top 5', 'best of', 'compilation', 'moments', 'clips', 'highlights', '#shorts'];
    const compilationCount = titles.filter(t => commonPrefixes.some(p => t.includes(p))).length;
    if (compilationCount / titles.length > 0.4) {
        flags.push({ type: 'Compilation / Reuse Risk', severity: 'High', detail: `${Math.round(compilationCount / titles.length * 100)}% of videos show compilation patterns. May face copyright claims on reused footage.` });
    }

    // Music-heavy Shorts: all Shorts + no description links
    const shortsPct = videos.filter(v => v.isShort).length / videos.length;
    if (shortsPct > 0.7 && !channelDescription.match(/original|music|produced by/i)) {
        flags.push({ type: 'Music-Heavy Shorts Dependency', severity: 'Medium', detail: `${Math.round(shortsPct * 100)}% Shorts. If using trending audio, monetization may be limited under YPP music policies.` });
    }

    // Extreme view inequality: 1 video with >50% of all views
    const totalViews = videos.reduce((s, v) => s + v.views, 0);
    const maxViews = Math.max(...videos.map(v => v.views));
    if (totalViews > 0 && maxViews / totalViews > 0.5 && videos.length >= 5) {
        flags.push({ type: 'Single-Video Dependency', severity: 'Medium', detail: `One video accounts for over ${Math.round(maxViews / totalViews * 100)}% of all views. Revenue and growth highly dependent on that video staying up.` });
    }

    // Very high posting frequency with short videos could signal spam-like behavior
    return flags;
}

export async function POST(req: Request) {
    try {
        const body = await req.json();
        const { channel, videos, topVideo } = body as {
            channel: { id: string; title: string; description: string; totalSubs: number; avgViewsPerVideo: number };
            videos: { id: string; title: string; views: number; publishedAt: string; duration: number; isShort: boolean; isOutperformer: boolean; outperformRatio: number }[];
            topVideo: { id: string; title: string; views: number; publishedAt: string; duration: number; isShort: boolean };
        };

        if (!channel || !videos?.length) {
            return NextResponse.json({ error: 'Missing channel or videos data' }, { status: 400 });
        }

        // 1. Trend Persistence Score (data-computed, instant)
        const trendPersistence = computeTrendPersistence(videos, channel.avgViewsPerVideo);

        // 2. Risk Flags (heuristic, instant)
        const riskFlags = computeRiskFlags(videos, channel.description || '');

        // 3. Format DNA + Packaging Analyzer via Gemini
        const titlesForAnalysis = videos
            .sort((a, b) => b.views - a.views)
            .slice(0, 20)
            .map((v, i) => `[#${i + 1} | ${(v.views / 1000).toFixed(0)}K views | ${v.duration < 60 ? 'SHORT' : `${Math.floor(v.duration / 60)}min`}] "${v.title}"`)
            .join('\n');

        const viralTitle = topVideo?.title || videos.sort((a, b) => b.views - a.views)[0]?.title || '';
        const viralDuration = topVideo?.duration || 0;
        const viralViews = topVideo?.views || 0;

        const prompt = `You are a YouTube content strategist doing forensic analysis on a channel's most successful content.

Channel: "${channel.title}" | ${(channel.totalSubs / 1000).toFixed(1)}K subs | Avg: ${(channel.avgViewsPerVideo / 1000).toFixed(0)}K views/video

TOP VIRAL VIDEO:
Title: "${viralTitle}"
Views: ${(viralViews / 1000).toFixed(0)}K
Duration: ${viralDuration < 60 ? `${viralDuration}s (Short)` : `${Math.floor(viralDuration / 60)}min ${viralDuration % 60}s`}

TOP 20 VIDEOS BY VIEWS:
${titlesForAnalysis}

Respond with ONLY a valid JSON object (no markdown, no code blocks):
{
  "packagingAnalyzer": {
    "titlePatternTag": "<one of: Curiosity Gap | Listicle | Challenge | Controversy | Before/After | Transformation | How-To | Beginner Trap | Hidden Feature | First Person Story | Reaction | Debate>",
    "titlePatternExplanation": "<1-2 sentences on why the viral title works psychologically>",
    "thumbnailStrategy": "<describe the likely thumbnail strategy based on the niche and title — faces/no faces, text overlay style, color palette, emotional trigger>",
    "hookPosition": "<estimate when the hook lands, e.g. 'First 3 seconds for Shorts', 'First 15-20 seconds for long-form'>",
    "hookType": "<one of: Shock/Surprise | Question | Controversy | Bold Claim | Relatable Problem | FOMO | Visual Hook>",
    "packagingTemplate": "<a fill-in-the-blank template the user can reuse, e.g. 'I [Did X] for [Time Period] — Here\\'s What Happened'>",
    "ctaStyle": "<estimate the likely CTA: None / Subscribe ask / Pinned comment / End screen funnel / Part 2 tease>"
  },
  "formatDNA": {
    "videoLength": "<e.g. '8-12 minutes' or 'Under 60 seconds (Short)'>",
    "pacing": "<estimate pace: Fast-cut / Standard / Slow-burn>",
    "onScreenText": "<High / Medium / Low — estimate how much text overlay based on niche patterns>",
    "topicAngle": "<the framing angle, e.g. 'Beginner mistake reveal', 'Expert simplification', 'First-person experiment', 'Listicle comparison'>",
    "postingContext": "<observation about optimal timing for this format>",
    "replicableElements": [
      "<specific element that can be replicated>",
      "<specific element that can be replicated>",
      "<specific element that can be replicated>"
    ],
    "creatorPlaybook": "<3-4 sentences: If I were starting a channel in this niche today, here is exactly what I would do based on this analysis>"
  }
}`;

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

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

        return NextResponse.json({
            trendPersistence,
            riskFlags,
            ...aiAnalysis,
        });

    } catch (err: any) {
        console.error('Channel analyze error:', err?.message);
        return NextResponse.json({ error: err?.message || 'Analysis failed' }, { status: 500 });
    }
}
