/**
 * Firestore 상태 진단 스크립트
 *
 * FloatingTermDetection 컴포넌트 미작동 원인 진단을 위해
 * Firestore의 현재 상태를 확인합니다.
 *
 * 사용법:
 *   cd /home/jay/projects/insuwiki/.worktrees/task-1724.1-dev5/nextapp
 *   npx ts-node ../scripts/checkFirestoreState.ts
 */

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

// ============================================================
// Firebase Admin 초기화
// ============================================================
if (!admin.apps.length) {
    const localKeyPath = '/home/jay/.config/gcloud/service-accounts/insuwiki-j2h-fa603f4f75f5.json';
    if (fs.existsSync(localKeyPath)) {
        try {
            const serviceAccount = JSON.parse(fs.readFileSync(localKeyPath, 'utf8'));
            admin.initializeApp({
                credential: admin.credential.cert(serviceAccount),
                projectId: 'insuwiki-j2h',
            });
        } catch {
            admin.initializeApp();
        }
    } else {
        admin.initializeApp();
    }
}
const db = admin.firestore();

// ============================================================
// 진단 함수들
// ============================================================

async function checkInsuranceTerms(): Promise<number> {
    const snapshot = await db.collection('insurance_terms').get();
    return snapshot.size;
}

async function checkDocuments(): Promise<{ total: number; withContent: number }> {
    const snapshot = await db.collection('documents').get();
    const total = snapshot.size;
    let withContent = 0;
    for (const doc of snapshot.docs) {
        const data = doc.data();
        if (data.content && String(data.content).trim().length > 0) {
            withContent++;
        }
    }
    return { total, withContent };
}

async function checkAiSuggestions(): Promise<{ sampledDocs: number; docsWithAiSuggestions: number }> {
    const snapshot = await db.collection('documents').limit(20).get();
    const sampledDocs = snapshot.size;
    let docsWithAiSuggestions = 0;

    for (const doc of snapshot.docs) {
        const subSnap = await db
            .collection('documents')
            .doc(doc.id)
            .collection('ai_suggestions')
            .limit(1)
            .get();
        if (!subSnap.empty) {
            docsWithAiSuggestions++;
        }
    }
    return { sampledDocs, docsWithAiSuggestions };
}

async function checkAiLinkingConfig(): Promise<{ exists: boolean; enabled?: boolean }> {
    const docRef = db.collection('config').doc('aiLinking');
    const snap = await docRef.get();
    if (!snap.exists) {
        return { exists: false };
    }
    const data = snap.data();
    return { exists: true, enabled: data?.enabled };
}

async function checkNormalizeMap(): Promise<{ exists: boolean }> {
    const docRef = db.collection('config').doc('normalizeMap');
    const snap = await docRef.get();
    return { exists: snap.exists };
}

// ============================================================
// 메인
// ============================================================

async function main(): Promise<void> {
    console.log('=== Firestore 상태 진단 시작 ===\n');

    // 1. insurance_terms 컬렉션
    const insuranceTermsCount = await checkInsuranceTerms();
    console.log('[1] insurance_terms 컬렉션');
    console.log(`    문서 수: ${insuranceTermsCount}`);
    console.log();

    // 2. documents 컬렉션
    const { total: docsTotal, withContent: docsWithContent } = await checkDocuments();
    console.log('[2] documents 컬렉션');
    console.log(`    전체 문서 수: ${docsTotal}`);
    console.log(`    content가 있는 문서 수: ${docsWithContent}`);
    console.log();

    // 3. ai_suggestions 서브컬렉션 (최대 20개 샘플)
    const { sampledDocs, docsWithAiSuggestions } = await checkAiSuggestions();
    console.log('[3] documents > ai_suggestions 서브컬렉션 (샘플 최대 20개)');
    console.log(`    샘플 문서 수: ${sampledDocs}`);
    console.log(`    ai_suggestions 있는 문서 수: ${docsWithAiSuggestions} / ${sampledDocs}`);
    console.log();

    // 3-2. ai_suggestions 상세 현황 (method/dismissed 분포)
    console.log('[3-2] ai_suggestions 상세 현황 (샘플 최대 20개 문서)');
    {
        const sampleSnap = await db.collection('documents').limit(20).get();
        const methodCount: Record<string, number> = {};
        let dismissedTrue = 0;
        let dismissedFalse = 0;
        let staticAndNotDismissed = 0;
        let totalSuggestions = 0;

        for (const doc of sampleSnap.docs) {
            const subSnap = await db
                .collection('documents')
                .doc(doc.id)
                .collection('ai_suggestions')
                .get();

            for (const s of subSnap.docs) {
                const data = s.data();
                totalSuggestions++;

                // method별 카운트
                const method: string = data.method ?? '(없음)';
                methodCount[method] = (methodCount[method] ?? 0) + 1;

                // dismissed 카운트
                if (data.dismissed === true) {
                    dismissedTrue++;
                } else {
                    dismissedFalse++;
                }

                // FloatingTermDetection 표시 조건
                if (data.method === 'static' && data.dismissed !== true) {
                    staticAndNotDismissed++;
                }
            }
        }

        console.log(`    총 ai_suggestions 수: ${totalSuggestions}`);
        console.log('    method별 분포:');
        for (const [method, count] of Object.entries(methodCount)) {
            console.log(`      - ${method}: ${count}개`);
        }
        console.log(`    dismissed=true: ${dismissedTrue}개`);
        console.log(`    dismissed=false(또는 미설정): ${dismissedFalse}개`);
        console.log(`    [FloatingTermDetection 표시 대상] method='static' AND dismissed≠true: ${staticAndNotDismissed}개`);
    }
    console.log();

    // 4. config/aiLinking
    const aiLinking = await checkAiLinkingConfig();
    console.log('[4] config/aiLinking');
    console.log(`    존재 여부: ${aiLinking.exists}`);
    if (aiLinking.exists) {
        console.log(`    enabled: ${aiLinking.enabled}`);
    }
    console.log();

    // 5. config/normalizeMap
    const normalizeMap = await checkNormalizeMap();
    console.log('[5] config/normalizeMap');
    console.log(`    존재 여부: ${normalizeMap.exists}`);
    console.log();

    console.log('=== 진단 완료 ===');
}

main()
    .then(() => process.exit(0))
    .catch((err) => {
        console.error('오류 발생:', err);
        process.exit(1);
    });
