/**
 * youtube-get-pending.ts
 *
 * Firestore에서 요약 대기 중인 유튜브 영상 목록을 조회하는 유틸리티 스크립트.
 * 아누(봇)가 이 스크립트를 실행하여 요약이 필요한 영상을 파악합니다.
 *
 * 사용법:
 *   npx ts-node scripts/youtube-get-pending.ts
 *   npx ts-node scripts/youtube-get-pending.ts --with-transcript --videoId <videoId>
 */

import * as admin from 'firebase-admin';
import * as fs from 'fs';
import * as path from 'path';
import * as dotenv from 'dotenv';

dotenv.config({ path: path.resolve(__dirname, '../.env.local') });

// ── Firebase Admin 초기화 ────────────────────────────────────────────────────
const localKeyPath = path.resolve(__dirname, '../temp.j2h/insuwiki-j2h-902be7d0b6f5.json');
if (!admin.apps.length) {
    let credential: admin.credential.Credential | undefined;
    if (fs.existsSync(localKeyPath)) {
        try {
            credential = admin.credential.cert(JSON.parse(fs.readFileSync(localKeyPath, 'utf8')));
        } catch { /* 무시 */ }
    }
    admin.initializeApp(
        credential
            ? { credential, projectId: 'insuwiki-j2h' }
            : undefined
    );
}

const db = admin.firestore();

// ── 인수 파싱 ────────────────────────────────────────────────────────────────
const args = process.argv.slice(2);
const withTranscript = args.includes('--with-transcript');
const videoIdIndex = args.indexOf('--videoId');
const videoId = videoIdIndex !== -1 ? args[videoIdIndex + 1] : undefined;

// ── 기본 모드: pending 영상 목록 조회 ─────────────────────────────────────────
async function listPendingVideos(): Promise<void> {
    console.error('[youtube-get-pending] youtube_summary_queue에서 pending 문서 조회 중...');

    const queueSnap = await db
        .collection('youtube_summary_queue')
        .where('status', '==', 'pending')
        .get();

    if (queueSnap.empty) {
        const result = { pendingCount: 0, videos: [] };
        process.stdout.write(JSON.stringify(result, null, 2) + '\n');
        process.exit(0);
    }

    console.error(`[youtube-get-pending] pending 문서 ${queueSnap.size}개 발견. youtube_knowledge 조회 중...`);

    const videos: object[] = [];

    for (const queueDoc of queueSnap.docs) {
        const queueData = queueDoc.data();
        const vid = queueData.videoId as string | undefined;

        if (!vid) {
            console.error(`[youtube-get-pending] 경고: 문서 ${queueDoc.id}에 videoId 필드 없음. 건너뜀.`);
            continue;
        }

        // youtube_knowledge에서 상세 정보 조회 (autoID 문서이므로 where 쿼리 사용)
        const knowledgeSnap = await db
            .collection('youtube_knowledge')
            .where('videoId', '==', vid)
            .limit(1)
            .get();

        if (knowledgeSnap.empty) {
            console.error(`[youtube-get-pending] 경고: youtube_knowledge에 videoId=${vid} 문서 없음.`);
            videos.push({
                videoId: vid,
                title: null,
                channelName: null,
                publishedAt: null,
                hasTranscript: false,
                driveTranscriptUrl: null,
                transcriptionSource: null,
            });
            continue;
        }

        const kd = knowledgeSnap.docs[0].data();

        // publishedAt 정규화 (Timestamp → ISO date string)
        let publishedAt: string | null = null;
        if (kd.publishedAt) {
            if (typeof kd.publishedAt.toDate === 'function') {
                publishedAt = kd.publishedAt.toDate().toISOString().split('T')[0];
            } else if (typeof kd.publishedAt === 'string') {
                publishedAt = kd.publishedAt;
            }
        }

        videos.push({
            videoId: vid,
            title: kd.title ?? null,
            channelName: kd.channelName ?? null,
            publishedAt,
            hasTranscript: kd.hasTranscript ?? false,
            driveTranscriptUrl: kd.driveTranscriptUrl ?? null,
            transcriptionSource: kd.transcriptionSource ?? null,
        });
    }

    const result = {
        pendingCount: videos.length,
        videos,
    };

    process.stdout.write(JSON.stringify(result, null, 2) + '\n');
    process.exit(0);
}

// ── --with-transcript 모드: 특정 영상의 전문 조회 ─────────────────────────────
async function getTranscript(targetVideoId: string): Promise<void> {
    console.error(`[youtube-get-pending] videoId=${targetVideoId} 정보 및 transcript 조회 중...`);

    // youtube_knowledge에서 기본 정보 조회 (autoID 문서이므로 where 쿼리 사용)
    const knowledgeSnap = await db
        .collection('youtube_knowledge')
        .where('videoId', '==', targetVideoId)
        .limit(1)
        .get();

    let title: string | null = null;
    let channelName: string | null = null;

    if (!knowledgeSnap.empty) {
        const kd = knowledgeSnap.docs[0].data();
        title = kd.title ?? null;
        channelName = kd.channelName ?? null;
    } else {
        console.error(`[youtube-get-pending] 경고: youtube_knowledge에 videoId=${targetVideoId} 문서 없음.`);
    }

    // youtube_transcripts에서 transcript 청크 조회
    const transcriptSnap = await db
        .collection('youtube_transcripts')
        .where('videoId', '==', targetVideoId)
        .orderBy('chunkIndex')
        .get();

    if (transcriptSnap.empty) {
        console.error(`[youtube-get-pending] 경고: youtube_transcripts에 videoId=${targetVideoId} 문서 없음.`);
        const result = {
            videoId: targetVideoId,
            title,
            channelName,
            transcript: null,
        };
        process.stdout.write(JSON.stringify(result, null, 2) + '\n');
        process.exit(0);
    }

    console.error(`[youtube-get-pending] transcript 청크 ${transcriptSnap.size}개 결합 중...`);

    const chunks = transcriptSnap.docs
        .map(doc => {
            const d = doc.data();
            return { chunkIndex: d.chunkIndex as number, text: (d.text as string) ?? '' };
        })
        .sort((a, b) => a.chunkIndex - b.chunkIndex);

    const transcript = chunks.map(c => c.text).join(' ');

    const result = {
        videoId: targetVideoId,
        title,
        channelName,
        transcript,
    };

    process.stdout.write(JSON.stringify(result, null, 2) + '\n');
    process.exit(0);
}

// ── 진입점 ────────────────────────────────────────────────────────────────────
async function main(): Promise<void> {
    if (withTranscript) {
        if (!videoId) {
            console.error('[youtube-get-pending] 오류: --with-transcript 사용 시 --videoId <videoId> 가 필요합니다.');
            process.exit(1);
        }
        await getTranscript(videoId);
    } else {
        await listPendingVideos();
    }
}

main().catch(err => {
    console.error('[youtube-get-pending] 치명적 오류:', err);
    process.exit(1);
});
