/**
 * config/aiLinking 시드 스크립트
 *
 * Firestore config/aiLinking 문서에 AI linking 설정을 시드합니다.
 *
 * 사용법:
 *   npx ts-node scripts/seed-ai-linking-config.ts           # 실제 실행
 *   npx ts-node scripts/seed-ai-linking-config.ts --dry-run  # dry-run 모드
 *
 * MT-6: aiLinking config 시드 스크립트
 * 생성일: 2026-03-22
 */

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

// ============================================================
// Firebase Admin 초기화
// ============================================================
if (!admin.apps.length) {
    const localKeyPath = path.resolve(__dirname, '../temp.j2h/insuwiki-j2h-902be7d0b6f5.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();
            console.warn('⚠️ 서비스 계정 키 파싱 실패 — 기본 인증 사용');
        }
    } else {
        admin.initializeApp();
    }
}

const db = admin.firestore();

// ============================================================
// aiLinking 설정 데이터
// ============================================================

interface StaticMatchingConfig {
    enabled: boolean;
    minConfidence: number;
    maxLinksPerDoc: number;
}

interface EmbeddingMatchingConfig {
    enabled: boolean;
    minSimilarity: number;
}

interface SemanticMatchingConfig {
    enabled: boolean;
}

interface AiLinkingConfig {
    // 기존 staticMatching.ts 호환 필드
    enabled: boolean;
    maxSuggestions: number;
    minConfidence: number;
    autoApproveThreshold: number;
    termsCacheTTL: number;
    // Phase 1 신규 구조 필드
    methods: string[];
    staticMatching: StaticMatchingConfig;
    embeddingMatching: EmbeddingMatchingConfig;
    semanticMatching: SemanticMatchingConfig;
}

const AI_LINKING_CONFIG: AiLinkingConfig = {
    // 기존 staticMatching.ts가 사용하는 필드 (하위 호환성 유지)
    enabled: true,               // AI linking 활성화 여부
    maxSuggestions: 5,           // 문서당 최대 AI 추천 수
    minConfidence: 70,           // 최소 신뢰도 (0-100)
    autoApproveThreshold: 95,    // 자동 승인 임계값 (이 이상이면 자동 활성화 - Phase 1-B)
    termsCacheTTL: 3600,         // 용어 캐시 TTL (초 단위, 1시간)
    // 새로운 Phase 1 구조 필드
    methods: ['static', 'embedding', 'semantic'],
    staticMatching: {
        enabled: true,
        minConfidence: 70,
        maxLinksPerDoc: 10,
    },
    embeddingMatching: {
        enabled: false,
        minSimilarity: 0.75,
    },
    semanticMatching: {
        enabled: false,
    },
};

// ============================================================
// 메인 로직
// ============================================================
async function seedAiLinkingConfig(dryRun: boolean): Promise<void> {
    console.log(`\n${'='.repeat(60)}`);
    console.log(`config/aiLinking 시드 시작 (${dryRun ? 'DRY-RUN 모드' : '실제 실행 모드'})`);
    console.log(`${'='.repeat(60)}\n`);

    console.log('📋 저장할 설정:');
    console.log(JSON.stringify(AI_LINKING_CONFIG, null, 2));

    if (dryRun) {
        console.log('\n[DRY-RUN] 위 설정이 config/aiLinking에 저장될 예정입니다.');
        console.log('실제 실행하려면 --dry-run 플래그 없이 실행하세요.');
    } else {
        // 기존 설정 확인
        const existingDoc = await db.collection('config').doc('aiLinking').get();
        if (existingDoc.exists) {
            const existingData = existingDoc.data();
            console.log('\n⚠️ 기존 설정이 존재합니다:');
            console.log(JSON.stringify(existingData, null, 2));
            console.log('\n새 설정으로 덮어씁니다 (merge)...');
        }

        await db.collection('config').doc('aiLinking').set(AI_LINKING_CONFIG, { merge: false });
        console.log('\n✅ config/aiLinking 저장 완료');
    }

    console.log(`\n${'='.repeat(60)}\n`);
}

// ============================================================
// 실행
// ============================================================
const isDryRun = process.argv.includes('--dry-run');

seedAiLinkingConfig(isDryRun)
    .then(() => process.exit(0))
    .catch(err => {
        console.error('\n❌ 시드 실패:', err);
        process.exit(1);
    });
