/**
 * Task I: youtube_channels 초기 시딩 스크립트
 * 
 * 채널:
 *   - 보험명의정닥터 (@보험명의정닥터)
 *   - ins-king       (@ins-king)
 *
 * 실행: npx ts-node scripts/seed-youtube-channels.ts
 *
 * NOTE: YouTube Data API로 핸들(@보험명의정닥터)을 실제 channelId(UCxxx...)로 변환합니다.
 *       YOUTUBE_API_KEY 환경 변수 필요.
 */

import * as admin from 'firebase-admin';
import * as path from 'path';
import * as dotenv from 'dotenv';
import { google } from 'googleapis';

dotenv.config({ path: path.join(__dirname, '../.env.local') });
dotenv.config({ path: path.join(__dirname, '../.env') });

if (!admin.apps.length) {
    admin.initializeApp({
        credential: admin.credential.cert(
            JSON.parse(process.env.GOOGLE_SERVICE_ACCOUNT_KEY || '{}')
        ),
        projectId: process.env.FIREBASE_PROJECT_ID,
    });
}
const db = admin.firestore();

// ── 등록할 채널 핸들 목록 ────────────────────────────────────────────────
const CHANNELS_TO_REGISTER = [
    {
        handle: '보험명의정닥터',        // @보험명의정닥터
        channelName: '보험명의정닥터',
        includeShorts: true,
    },
    {
        handle: 'ins-king',              // @ins-king
        channelName: '인스킹 ins-king',
        includeShorts: true,
    },
];

async function resolveChannelId(
    youtube: ReturnType<typeof google.youtube>,
    handle: string
): Promise<string | null> {
    // YouTube Data API v3 channels.list — forHandle 파라미터
    const res = await youtube.channels.list({
        part: ['id', 'snippet'],
        forHandle: handle,
    } as any); // forHandle은 최신 API에 추가됨

    const item = res.data.items?.[0];
    if (!item?.id) {
        console.warn(`⚠️ 핸들 "${handle}"의 Channel ID를 찾지 못했습니다.`);
        return null;
    }

    console.log(`✅ ${handle} → Channel ID: ${item.id} (${item.snippet?.title})`);
    return item.id;
}

async function main() {
    const youtubeApiKey = process.env.YOUTUBE_API_KEY;
    if (!youtubeApiKey) {
        console.error('❌ YOUTUBE_API_KEY 환경 변수 없음');
        process.exit(1);
    }

    const youtube = google.youtube({ version: 'v3', auth: youtubeApiKey });

    console.log('🚀 유튜브 채널 시딩 시작...\n');

    for (const ch of CHANNELS_TO_REGISTER) {
        const channelId = await resolveChannelId(youtube, ch.handle);
        if (!channelId) continue;

        const docId = `ch_${ch.handle.replace(/[^a-zA-Z0-9가-힣]/g, '_')}`;

        await db.collection('youtube_channels').doc(docId).set({
            channelId,
            channelName: ch.channelName,
            handle: ch.handle,
            includeShorts: ch.includeShorts,
            isActive: true,
            lastCrawledAt: admin.firestore.Timestamp.fromDate(
                // 처음에는 7일 전부터 수집 (최근 1주일치)
                new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
            ),
            createdAt: admin.firestore.FieldValue.serverTimestamp(),
        }, { merge: true });

        console.log(`📺 등록 완료: ${ch.channelName} (${channelId})`);
    }

    console.log('\n✅ Firestore youtube_channels 시딩 완료!');
    console.log('👉 다음 단계: firebase deploy --only functions:crawlYoutubeChannels');
    process.exit(0);
}

main().catch(err => {
    console.error('❌ 오류:', err);
    process.exit(1);
});
