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

// Initialize Firebase Admin (Make sure your GOOGLE_APPLICATION_CREDENTIALS is set)
// Usage (dry-run): ts-node scripts/backfill-authority-tier.ts
// Usage (execute): ts-node scripts/backfill-authority-tier.ts --execute

if (!admin.apps.length) {
  admin.initializeApp();
}

const db = admin.firestore();

// ── TIER_MAP (canonical source: nextapp/src/lib/constants.ts) ───────────────
const TIER_MAP: Record<string, number> = {
  policy_pdf: 1,
  regulation: 1.5,
  newsletter: 2,
  court_ruling: 2,
  wiki_editorial: 3,
  kakao_expert: 3.5,
  kakao_community: 4,
  youtube: 4,
  user_submitted: 4,
};

const BATCH_SIZE = 500;
const NULL_SOURCE_TYPE_TIER = 6;
const NULL_DOCS_OUTPUT_FILE = path.join(__dirname, 'manual-classification-needed.json');

// ── 타입 정의 ─────────────────────────────────────────────────────────────────

interface BackfillResult {
  total: number;
  updated: number;
  skipped: number; // already had authorityTier
  nullSourceType: number;
  errors: number;
}

interface NullDoc {
  docId: string;
  title: string;
}

// ── 핵심 함수 ─────────────────────────────────────────────────────────────────

async function backfillBatch(
  docs: FirebaseFirestore.QueryDocumentSnapshot[],
  dryRun: boolean,
): Promise<{ updated: number; skipped: number; nullSourceType: number; errors: number; nullDocs: NullDoc[] }> {
  let updated = 0;
  let skipped = 0;
  let nullSourceType = 0;
  let errors = 0;
  const nullDocs: NullDoc[] = [];

  const batch = db.batch();

  for (const doc of docs) {
    try {
      const data = doc.data();

      // 이미 authorityTier가 있으면 스킵
      if (data.authorityTier !== undefined && data.authorityTier !== null) {
        skipped++;
        continue;
      }

      const sourceType: string | null = data.sourceType ?? null;
      const tier = sourceType ? (TIER_MAP[sourceType] ?? NULL_SOURCE_TYPE_TIER) : NULL_SOURCE_TYPE_TIER;

      if (!sourceType) {
        nullSourceType++;
        nullDocs.push({ docId: doc.id, title: data.title ?? '' });
      }

      batch.update(doc.ref, { authorityTier: tier });
      updated++;
    } catch (err) {
      console.error(`[ERROR] 문서 처리 중 오류 발생 (id=${doc.id}):`, err);
      errors++;
    }
  }

  if (!dryRun && updated > 0) {
    await batch.commit();
  }

  return { updated, skipped, nullSourceType, errors, nullDocs };
}

async function backfillAuthorityTier(dryRun: boolean): Promise<BackfillResult> {
  console.log(`[INFO] authorityTier 백필 시작 (dryRun=${dryRun})`);

  const result: BackfillResult = {
    total: 0,
    updated: 0,
    skipped: 0,
    nullSourceType: 0,
    errors: 0,
  };

  const allNullDocs: NullDoc[] = [];

  // Firestore는 한 번에 전체를 가져오는 것이 일반적이지만
  // 대용량 처리를 위해 500건씩 배치로 나누어 처리
  const snapshot = await db.collection('documents').get();
  result.total = snapshot.docs.length;

  console.log(`[INFO] 전체 문서 수: ${result.total}`);

  for (let i = 0; i < snapshot.docs.length; i += BATCH_SIZE) {
    const batchDocs = snapshot.docs.slice(i, i + BATCH_SIZE);
    const batchNum = Math.floor(i / BATCH_SIZE) + 1;
    const totalBatches = Math.ceil(snapshot.docs.length / BATCH_SIZE);

    console.log(`[INFO] 배치 ${batchNum}/${totalBatches} 처리 중 (${batchDocs.length}건)...`);

    const batchResult = await backfillBatch(batchDocs, dryRun);

    result.updated += batchResult.updated;
    result.skipped += batchResult.skipped;
    result.nullSourceType += batchResult.nullSourceType;
    result.errors += batchResult.errors;
    allNullDocs.push(...batchResult.nullDocs);
  }

  // sourceType null 문서를 파일로 기록
  if (allNullDocs.length > 0) {
    if (!dryRun) {
      fs.writeFileSync(NULL_DOCS_OUTPUT_FILE, JSON.stringify(allNullDocs, null, 2), 'utf-8');
      console.log(`[INFO] null sourceType 문서 ${allNullDocs.length}건을 ${NULL_DOCS_OUTPUT_FILE}에 기록했습니다.`);
    } else {
      console.log(`[DRY-RUN] null sourceType 문서 ${allNullDocs.length}건 (파일 미생성)`);
    }
  }

  return result;
}

async function main() {
  const dryRun = !process.argv.includes('--execute');

  if (dryRun) {
    console.log('[DRY-RUN] --execute 플래그 없이 실행 중입니다. 실제 쓰기는 발생하지 않습니다.');
    console.log('[DRY-RUN] 실제 실행: ts-node scripts/backfill-authority-tier.ts --execute\n');
  } else {
    console.log('[EXECUTE] 실제 Firestore 쓰기가 실행됩니다.\n');
  }

  const result = await backfillAuthorityTier(dryRun);

  console.log('\n========== 백필 완료 요약 ==========');
  console.log(`전체 문서 수    : ${result.total}`);
  console.log(`백필 완료 수    : ${result.updated}${dryRun ? ' (dry-run)' : ''}`);
  console.log(`스킵 수         : ${result.skipped} (이미 authorityTier 있음)`);
  console.log(`null sourceType : ${result.nullSourceType} (authorityTier=6 설정됨)`);
  console.log(`오류 수         : ${result.errors}`);
  console.log('=====================================');
}

main().catch((err) => {
  console.error('[FATAL]', err);
  process.exit(1);
});
