// /api/discover/family-tree — Niche Family Tree
// Uses ytGet() for automatic key rotation on 403/quota errors.

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

const CATEGORY_MAP: Record<string, string> = {
    '1': 'Film & Animation', '2': 'Autos & Vehicles', '10': 'Music',
    '15': 'Pets & Animals', '17': 'Sports', '18': 'Short Movies',
    '19': 'Travel & Events', '20': 'Gaming', '21': 'Videoblogging',
    '22': 'People & Blogs', '23': 'Comedy', '24': 'Entertainment',
    '25': 'News & Politics', '26': 'Howto & Style', '27': 'Education',
    '28': 'Science & Technology', '29': 'Nonprofits & Activism',
};

export async function GET(req: Request) {
    const { searchParams } = new URL(req.url);
    const niche = searchParams.get('niche');
    if (!niche) return NextResponse.json({ error: 'niche param required' }, { status: 400 });

    try {
        // 1. Top channels for niche (search.list = 100 units, rotated)
        const searchData = await ytGet('/search', {
            q: niche, type: 'channel', part: 'snippet', maxResults: 5,
        });
        const channelIds: string[] = (searchData.items || []).map((c: any) => c.id.channelId).filter(Boolean);

        if (!channelIds.length) {
            return NextResponse.json({
                tree: {
                    niche,
                    parent: ['Entertainment'],
                    channels: [],
                    siblings: [`best ${niche}`, `${niche} for beginners`],
                    children: [`${niche} for beginners`, `advanced ${niche}`, `${niche} 2025`],
                },
            });
        }

        // 2. Channel details (channels.list = 1 unit)
        const detailData = await ytGet('/channels', {
            id: channelIds.join(','),
            part: 'snippet,topicDetails,statistics',
        });
        const channels = detailData.items || [];

        // 3. Parent from topicDetails
        const topicUrls: string[] = [];
        for (const ch of channels) {
            topicUrls.push(...(ch.topicDetails?.topicCategories || []));
        }
        const parentLabels = [...new Set(topicUrls.map(url => {
            const m = url.match(/wiki\/(.+)$/);
            return m ? decodeURIComponent(m[1].replace(/_/g, ' ')) : null;
        }).filter(Boolean))];

        // 4. Sibling niches — ONE search call (was 2, saves 100 quota units)
        const siblingData = await ytGet('/search', {
            q: `${niche} tips beginners`, type: 'channel', part: 'snippet', maxResults: 4,
        });
        const siblingNames = (siblingData.items || []).map((c: any) => c.snippet.channelTitle);

        // 5. Child sub-niches from top videos (search.list = 100 units, rotated)
        const videoData = await ytGet('/search', {
            q: niche, type: 'video', part: 'snippet', order: 'viewCount', maxResults: 15,
        });
        const childTitles: string[] = (videoData.items || []).map((v: any) => v.snippet.title);

        const stopWords = new Set(['the', 'a', 'an', 'and', 'or', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'how', 'why', 'what']);
        const wordFreq = new Map<string, number>();
        for (const title of childTitles) {
            const words = title.toLowerCase().replace(/[^a-z\s]/g, '').split(/\s+/).filter(w => w.length > 4 && !stopWords.has(w));
            for (const w of words) wordFreq.set(w, (wordFreq.get(w) || 0) + 1);
        }
        const childKeywords = [...wordFreq.entries()]
            .filter(([, c]) => c >= 2).sort((a, b) => b[1] - a[1]).slice(0, 6)
            .map(([w]) => `${niche} ${w}`);

        return NextResponse.json({
            tree: {
                niche,
                parent: parentLabels.slice(0, 3),
                channels: channels.map((ch: any) => ({
                    id: ch.id,
                    title: ch.snippet?.title,
                    subs: parseInt(ch.statistics?.subscriberCount || '0'),
                    thumbnail: ch.snippet?.thumbnails?.default?.url,
                })),
                siblings: [...new Set(siblingNames)].slice(0, 6),
                children: childKeywords.length
                    ? childKeywords
                    : [`${niche} for beginners`, `advanced ${niche}`, `${niche} 2025`],
            },
        });

    } catch (err: any) {
        console.error('[FamilyTree]', err);
        if (err?.quotaExhausted) {
            return NextResponse.json({ error: err.message, quotaExhausted: true }, { status: 503 });
        }
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}
