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';

// Tier 1 countries (high ad revenue)
const TIER1_COUNTRIES = new Set(['US', 'GB', 'CA', 'AU', 'NZ', 'IE', 'DE', 'NL', 'SE', 'NO', 'DK', 'CH', 'AT', 'BE', 'FR']);
const TIER2_COUNTRIES = new Set(['JP', 'KR', 'SG', 'HK', 'TW', 'IT', 'ES', 'PL', 'CZ', 'PT', 'FI', 'MX', 'BR', 'AR']);

function getGeographyTier(countries: string[]): { tier: string; label: string; color: string; countries: string[] } {
  const tier1Count = countries.filter(c => TIER1_COUNTRIES.has(c)).length;
  const tier2Count = countries.filter(c => TIER2_COUNTRIES.has(c)).length;
  const total = countries.length || 1;
  if (tier1Count / total >= 0.5) {
    return { tier: '1', label: '🟢 Tier 1 — High RPM', color: '#22c55e', countries };
  }
  if ((tier1Count + tier2Count) / total >= 0.4) {
    return { tier: '2', label: '🟡 Tier 2 — Medium RPM', color: '#eab308', countries };
  }
  return { tier: '3', label: '🔴 Tier 3 — Lower RPM', color: '#ef4444', countries };
}

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const { keyword, channels } = body as {
      keyword: string;
      channels: {
        id: string;
        title: string;
        description: string;
        country: string;
        viewCount: string;
        subscriberCount: string;
      }[];
    };

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

    // --- Data-computed: Geography Tier ---
    const countries = channels.map(c => c.country).filter(Boolean);
    const geography = getGeographyTier(countries);

    // --- Data-computed: Upload frequency (needs video fetch per top channel) ---
    // For niche-level, we'll estimate from the AI prompt instead

    // --- Build Gemini prompt ---
    const topChannels = channels.slice(0, 15);
    const channelSummaries = topChannels.map(c =>
      `Channel: "${c.title}" | Subs: ${c.subscriberCount} | Views: ${c.viewCount}\nDescription: ${c.description?.slice(0, 300) || 'N/A'}`
    ).join('\n\n---\n\n');

    const prompt = `You are a YouTube niche research analyst. Analyze this niche: "${keyword}"

Here are the top channels in this niche:

${channelSummaries}

Respond with ONLY a valid JSON object (no markdown, no code blocks) with exactly this structure:
{
  "facelessScore": <number 0-100, where 100 = completely faceless/automatable, 0 = requires on-camera personality>,
  "facelessReasoning": "<2-3 sentences explaining why>",
  "facelessLabel": "<one of: Fully Automatable | Mostly Faceless | Mixed | Personality-Driven>",

  "evergreen": <true/false, true if consistent year-round demand>,
  "evergreenLabel": "<one of: Evergreen | Seasonal | Trend-Based | Mixed>",
  "evergreenReasoning": "<2 sentences explaining>",

  "uploadFrequency": "<e.g. '3-5x per week' or '1-2x per month'>",
  "effortLevel": "<one of: Very High | High | Medium | Low>",
  "effortReasoning": "<1-2 sentences>",

  "titlePatterns": [
    "<title framework pattern 1>",
    "<title framework pattern 2>",
    "<title framework pattern 3>"
  ],

  "microNiches": [
    { "name": "<sub-niche name>", "description": "<1 sentence>", "opportunity": "<High|Medium|Low>" },
    { "name": "<sub-niche name>", "description": "<1 sentence>", "opportunity": "<High|Medium|Low>" },
    { "name": "<sub-niche name>", "description": "<1 sentence>", "opportunity": "<High|Medium|Low>" },
    { "name": "<sub-niche name>", "description": "<1 sentence>", "opportunity": "<High|Medium|Low>" }
  ],

  "missingVideoIdentifier": {
    "summary": "<2 sentences: what broad subtopic area is clearly demanded but severely underserved in this niche>",
    "makeThisFirst": {
      "title": "<the single most impactful video title a new creator should make first to capture uncontested demand>",
      "why": "<2 sentences: why this specific video would win — what gap it fills and what search intent it captures>",
      "searchabilityScore": <number 0-100, estimate of how searchable/discoverable this video would be>
    },
    "gaps": [
      { "topic": "<specific underserved subtopic>", "demand": "<High|Medium>", "competition": "<Low|Medium>", "videoIdea": "<specific video title>", "searchabilityScore": <number 0-100> },
      { "topic": "<specific underserved subtopic>", "demand": "<High|Medium>", "competition": "<Low|Medium>", "videoIdea": "<specific video title>", "searchabilityScore": <number 0-100> },
      { "topic": "<specific underserved subtopic>", "demand": "<High|Medium>", "competition": "<Low|Medium>", "videoIdea": "<specific video title>", "searchabilityScore": <number 0-100> }
    ]
  },

  "titleThumbnailClusters": [
    {
      "cluster": "<pattern cluster name, e.g. 'Number + Curiosity Gap'>",
      "titlePattern": "<fill-in-the-blank template, e.g. '[Number] Things Nobody Tells You About [X]'>",
      "thumbnailStyle": "<describe the visual approach: e.g. 'Face with shocked expression + bold red text overlay' or 'No face, product close-up + minimal text'>",
      "performanceMultiplier": "<e.g. '2.4x avg views' — estimated outperformance vs typical video in this niche>",
      "exampleTitle": "<a concrete example title using this pattern for the ${keyword} niche>"
    },
    {
      "cluster": "<pattern cluster name>",
      "titlePattern": "<fill-in-the-blank template>",
      "thumbnailStyle": "<describe the visual approach>",
      "performanceMultiplier": "<estimated multiplier>",
      "exampleTitle": "<concrete example>"
    },
    {
      "cluster": "<pattern cluster name>",
      "titlePattern": "<fill-in-the-blank template>",
      "thumbnailStyle": "<describe the visual approach>",
      "performanceMultiplier": "<estimated multiplier>",
      "exampleTitle": "<concrete example>"
    }
  ],

  "replicationDifficulty": {
    "score": <number 0-100, where 100 = nearly impossible to replicate, 0 = anyone can copy it tonight>,
    "label": "<one of: Very Easy | Easy | Moderate | Hard | Very Hard>",
    "dimensions": {
      "onCameraRequired": <true/false>,
      "equipmentLevel": "<one of: Smartphone only | Basic setup ($200-500) | Intermediate ($500-2000) | Professional ($2000+)>",
      "specializedKnowledge": "<one of: None | Basic | Intermediate | Expert>",
      "uniqueVoiceRequired": <true/false>,
      "editingComplexity": "<one of: None | Simple cuts | Moderate | Advanced | Cinematic>"
    },
    "newCreatorPath": "<2-3 sentences: the realistic lowest-effort path a new creator could take to enter this niche and compete>"
  },

  "uploadFrequencyCorrelation": {
    "optimalFrequency": "<e.g. '2-3x per week' — the sweet spot based on top performers>",
    "insight": "<2 sentences: do daily posters outperform weekly ones in this niche? What does the data suggest?>",
    "fastGrowthStrategy": "<1-2 sentences: what posting strategy would give the fastest traction for a new channel?>"
  },

  "seasonality": {
    "pattern": "<one of: Year-Round | Monthly Cycle | Quarterly Peaks | Holiday-Driven | Event-Driven | Academic Calendar>",
    "peakMonths": ["<month name>", "<month name>"],
    "lowMonths": ["<month name>"],
    "externalTriggers": ["<external event that causes spikes>"],
    "recommendation": "<1-2 sentences on best time to launch or scale in this niche>"
  },

  "competitorNetwork": {
    "archetypes": [
      { "type": "<channel archetype>", "description": "<1 sentence>", "saturated": <true/false> },
      { "type": "<channel archetype>", "description": "<1 sentence>", "saturated": <true/false> },
      { "type": "<channel archetype>", "description": "<1 sentence>", "saturated": <true/false> }
    ],
    "collaborationLikelihood": "<High|Medium|Low>",
    "audienceOverlapClusters": ["<related niche>", "<related niche>", "<related niche>"],
    "blueOceanArchetype": "<channel type that doesn't exist yet but the audience clearly wants>"
  },

  "nicheSummary": "<3-4 sentences summarizing this niche, its audience, and the biggest opportunity for a new creator>"
}`;

    const raw = await geminiPrompt(prompt);

    // Parse JSON safely - strip any markdown wrapping
    const jsonStr = raw.replace(/```json\n?/g, '').replace(/```\n?/g, '').trim();
    let aiAnalysis: Record<string, unknown>;
    try {
      aiAnalysis = JSON.parse(jsonStr);
    } catch {
      // Try to extract JSON from the response
      const match = jsonStr.match(/\{[\s\S]*\}/);
      aiAnalysis = match ? JSON.parse(match[0]) : { error: 'Failed to parse AI response', raw: jsonStr.slice(0, 500) };
    }

    return NextResponse.json({
      geography,
      ...aiAnalysis,
    });

  } catch (err: any) {
    const msg = err?.message || 'AI analysis failed';
    console.error('Niche analyze error:', msg);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
