/**
 * Task A: Google Drive InsuWiki_RAG/ 폴더 파싱 → insurance_metadata 자동 시딩
 * Spec: docs/specs/260225-insuwiki-rag-spec-v2.md § 3
 *
 * 실행: npx ts-node scripts/seed-insurance-metadata.ts
 * 필수 환경 변수: GOOGLE_SERVICE_ACCOUNT_KEY, GOOGLE_DRIVE_ROOT_FOLDER_ID, FIREBASE_PROJECT_ID 등
 *
 * 폴더 구조:
 *   InsuWiki_RAG/
 *   ├── 01_약관/
 *   │   ├── 생명보험/삼성생명/삼성생명_퍼펙트종신_2403.pdf
 *   │   └── 손해보험/현대해상/현대해상_운전자보험_2501.pdf
 *   ├── 02_소식지/
 *   └── 03_보험료테이블/
 */

import { google } from 'googleapis';
import * as admin from 'firebase-admin';
import * as path from 'path';
import * as dotenv from 'dotenv';

dotenv.config({ path: path.join(__dirname, '../.env.local') });
dotenv.config({ path: path.join(__dirname, '../.env') });

// Firebase Admin 초기화
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();

// Google Drive 인증
const getDrive = () => {
    const auth = new google.auth.GoogleAuth({
        credentials: JSON.parse(process.env.GOOGLE_SERVICE_ACCOUNT_KEY || '{}'),
        scopes: ['https://www.googleapis.com/auth/drive.readonly'],
    });
    return google.drive({ version: 'v3', auth });
};

// ── 경로 파싱 유틸 ──────────────────────────────────────────────────────
const CATEGORY_MAP: Record<string, 'life' | 'non_life' | 'variable'> = {
    '생명보험': 'life',
    '손해보험': 'non_life',
    '변액보험': 'variable',
};

function parseFileName(fileName: string): { productName: string; effectiveDate: string } | null {
    // 삼성생명_퍼펙트종신_2403.pdf → { productName: "퍼펙트종신", effectiveDate: "2024-03" }
    const base = fileName.replace(/\.pdf$/i, '');
    const parts = base.split('_');
    if (parts.length < 3) return null;

    const yymm = parts[parts.length - 1]; // "2403"
    const year = `20${yymm.slice(0, 2)}`;
    const month = yymm.slice(2, 4);
    const productName = parts.slice(1, -1).join('_');

    return { productName, effectiveDate: `${year}-${month}` };
}

function toCompanyId(companyName: string): string {
    return companyName
        .replace(/\s/g, '_')
        .replace(/생명/g, 'life')
        .replace(/해상/g, 'marine')
        .replace(/손보/g, 'nonlife')
        .toLowerCase();
}

// ── Drive API 쿼리 이스케이핑 ──────────────────────────────────────────────
function escapeDriveQuery(value: string): string {
    return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
}

// ── Drive 폴더 재귀 탐색 ─────────────────────────────────────────────────
async function listFilesInFolder(drive: ReturnType<typeof getDrive>, folderId: string, pathParts: string[]): Promise<void> {
    const res = await drive.files.list({
        q: `'${escapeDriveQuery(folderId)}' in parents and trashed = false`,
        fields: 'files(id, name, mimeType)',
        pageSize: 200,
    });

    const files = res.data.files || [];

    for (const file of files) {
        if (!file.id || !file.name) continue;

        if (file.mimeType === 'application/vnd.google-apps.folder') {
            // 재귀: 하위 폴더 탐색
            await listFilesInFolder(drive, file.id, [...pathParts, file.name]);
        } else if (file.mimeType === 'application/pdf' && pathParts[0]?.startsWith('01_약관')) {
            // PDF 파일 → insurance_metadata 시딩
            await upsertInsuranceMetadata(file.id, file.name, pathParts);
        } else if (file.mimeType === 'application/pdf' && pathParts[0]?.startsWith('02_소식지')) {
            console.log(`📰 소식지 감지 (추후 인덱싱): ${pathParts.join('/')}/${file.name}`);
        } else if (file.mimeType === 'application/pdf' && pathParts[0]?.startsWith('03_보험료테이블')) {
            console.log(`💰 보험료 테이블 감지 (Phase 0 ETL): ${pathParts.join('/')}/${file.name}`);
        }
    }
}

async function upsertInsuranceMetadata(driveFileId: string, fileName: string, pathParts: string[]): Promise<void> {
    // 경로 파싱: ["01_약관", "생명보험", "삼성생명"]
    const categoryFolder = pathParts[1] || '';
    const companyName = pathParts[2] || '';

    const category = CATEGORY_MAP[categoryFolder] || 'life';
    const companyId = toCompanyId(companyName);

    const parsed = parseFileName(fileName);
    if (!parsed) {
        console.warn(`⚠️ 파일명 파싱 실패: ${fileName}`);
        return;
    }

    const { productName, effectiveDate } = parsed;
    const productId = `${companyId}_${productName.replace(/\s/g, '_').toLowerCase()}_${effectiveDate.replace('-', '')}`;

    const docId = productId;
    const metadata = {
        companyId,
        companyName,
        productId,
        productName,
        category,
        driveFileId,
        driveFileName: fileName,
        effectiveDateRange: { start: effectiveDate },
        isSalesStopped: false,    // 기본값: 판매 중. 수동으로 갱신 가능
        isActive: true,
        updatedAt: admin.firestore.FieldValue.serverTimestamp(),
        createdAt: admin.firestore.FieldValue.serverTimestamp(),
    };

    await db.collection('insurance_metadata').doc(docId).set(metadata, { merge: true });
    console.log(`✅ insurance_metadata upsert: ${companyName} / ${productName} (${effectiveDate})`);
}

// ── 메인 실행 ──────────────────────────────────────────────────────────────
async function main() {
    const rootFolderId = process.env.GOOGLE_DRIVE_FOLDER_ID;
    if (!rootFolderId) {
        console.error('❌ GOOGLE_DRIVE_FOLDER_ID 환경 변수 없음');
        process.exit(1);
    }

    const drive = getDrive();
    console.log('🚀 insurance_metadata 자동 시딩 시작...');
    console.log(`📁 루트 폴더 ID: ${rootFolderId}`);

    await listFilesInFolder(drive, rootFolderId, []);

    console.log('\n✅ 완료! Firestore insurance_metadata 컬렉션을 확인하세요.');
    process.exit(0);
}

main().catch(err => {
    console.error('❌ 오류:', err);
    process.exit(1);
});
