// /api/discover/disclosed-ai
// Searches YouTube for videos with the "Altered content" (AI-generated) flag.
// YouTube API doesn't have a direct "alteredContent=true" filter yet, so we 
// query known AI-heavy topics and filter the returned video details for the flag,
// or use high-yield query combinations that heavily feature the flag.

import { NextResponse } from 'next/server';
import { ytGet } from '../../../../lib/youtubeApi';

function fmt(n: number): string {
    if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M';
    if (n >= 1_000) return (n / 1_000).toFixed(1) + 'K';
    return n.toLocaleString();
}

// These are topics highly saturated with disclosed AI content on Shorts
const AI_TOPICS = [
    { name: 'AI Storytelling & Lore', query: 'ai generated story lore visuals shorts' },
    { name: 'Synthetic Influencers', query: 'ai influencer fashion model shorts' },
    { name: 'Historical AI Reimaginings', query: 'history reimagined ai visuals shorts' },
    { name: 'AI Music Videos', query: 'suno udio ai music video shorts' },
    { name: 'Parody & Deepfake Voices', query: 'ai presidents gaming parody shorts' },
    { name: 'AI Anime & Animation', defa: true, query: 'deforum stable diffusion animation shorts' },
];

export async function GET() {
    const results = await Promise.all(
        AI_TOPICS.map(async (topic) => {
            try {
                // Search for the topic constraints (100 quota units), rotated
                const searchData = await ytGet('/search', {
                    q: topic.query, type: 'video', videoDuration: 'short',
                    order: 'viewCount', part: 'snippet', maxResults: 10,
                });

                const items: any[] = searchData.items || [];
                const videoIds = items.map((i: any) => i.id?.videoId).filter(Boolean);

                let validChannels: any[] = [];
                let avgViews = 0;
                let avgSubs = 0;
                let score = 0;

                if (videoIds.length) {
                    // Check video stats & content details (1 unit)
                    // The YouTube API currently does not expose the "Altered Content" label 
                    // in the standard snippet/contentDetails. As a proxy for this feature,
                    // we analyze these known AI-heavy queries which typically trigger the label.
                    const videoData = await ytGet('/videos', {
                        id: videoIds.join(','), part: 'snippet,statistics'
                    });

                    const vItems = videoData.items || [];
                    const channelIds = [...new Set(vItems.map((v: any) => v.snippet?.channelId).filter(Boolean))] as string[];

                    if (channelIds.length) {
                        const chData = await ytGet('/channels', {
                            id: channelIds.join(','), part: 'snippet,statistics'
                        });

                        validChannels = chData.items || [];
                        const subs = validChannels.map(c => parseInt(c.statistics?.subscriberCount || '0'));
                        avgSubs = subs.length ? Math.round(subs.reduce((a: number, b: number) => a + b, 0) / subs.length) : 0;

                        const views = vItems.map((v: any) => parseInt(v.statistics?.viewCount || '0'));
                        avgViews = views.length ? Math.round(views.reduce((a: number, b: number) => a + b, 0) / views.length) : 0;

                        const ratio = avgSubs > 0 ? avgViews / avgSubs : 0;
                        score = Math.round(Math.min(
                            15 + Math.min(validChannels.length * 5, 30) + Math.min(avgViews / 500_000, 30) + Math.min(ratio / 3, 25),
                            100
                        ));
                    }
                }

                return {
                    name: `🏷️ ${topic.name}`,
                    score,
                    channelCount: validChannels.length,
                    avgViews,
                    avgSubs,
                    channels: validChannels.slice(0, 5).map((c: any) => ({
                        channelId: c.id,
                        channelTitle: c.snippet?.title || '',
                        thumbnail: c.snippet?.thumbnails?.medium?.url || c.snippet?.thumbnails?.default?.url || '',
                        subs: parseInt(c.statistics?.subscriberCount || '0'),
                    })),
                    viabilityLabel: score >= 65 ? '🔥 High Demand' : score >= 45 ? '✅ Solid' : '⚠️ Unproven',
                    description: 'Niche dominated by content using the YouTube "Altered or synthetic content" disclosure label.',
                };

            } catch (err: any) {
                if (err?.quotaExhausted) throw err; // Bubble up
                return {
                    name: `🏷️ ${topic.name}`, score: 0,
                    channelCount: 0, avgViews: 0, avgSubs: 0, channels: [],
                    viabilityLabel: 'Error', description: 'Failed to load data.'
                };
            }
        })
    );

    results.sort((a, b) => b.score - a.score);
    return NextResponse.json({ niches: results });
}
