/**
 * 독립 검증: documents 컬렉션에서 </u 패턴 존재 여부 확인
 */
import * as admin from 'firebase-admin';
import * as path from 'path';
import * as fs from 'fs';

if (!admin.apps.length) {
    const localKeyPath = path.resolve(__dirname, '../temp.j2h/insuwiki-j2h-902be7d0b6f5.json');
    if (fs.existsSync(localKeyPath)) {
        const serviceAccount = JSON.parse(fs.readFileSync(localKeyPath, 'utf8'));
        admin.initializeApp({
            credential: admin.credential.cert(serviceAccount),
            projectId: 'insuwiki-j2h',
        });
    } else {
        admin.initializeApp();
    }
}

const db = admin.firestore();

async function verify() {
    const collections = ['documents', 'dailyNotes', 'drafts'];

    for (const col of collections) {
        const snapshot = await db.collection(col).get();
        console.log(`\n[${col}] 총 문서: ${snapshot.size}개`);

        let brokenCount = 0;
        let ulCount = 0;
        let hasContentField = 0;

        for (const doc of snapshot.docs) {
            const data = doc.data();
            const content = data['content'];

            if (typeof content === 'string') {
                hasContentField++;

                // 깨진 밑줄 태그 검색 (</u 뒤에 > 이외 문자)
                const brokenMatches = content.match(/<\/u(?![>l])/g);
                if (brokenMatches) {
                    brokenCount++;
                    console.log(`  깨진 태그 발견: ${col}/${doc.id} (${brokenMatches.length}건)`);
                    // 주변 컨텍스트 출력
                    for (const match of brokenMatches) {
                        const idx = content.indexOf(match);
                        const ctx = content.substring(Math.max(0, idx - 30), Math.min(content.length, idx + 30));
                        console.log(`    컨텍스트: ...${JSON.stringify(ctx)}...`);
                    }
                }

                // </ul> 태그 존재 확인
                const ulMatches = content.match(/<\/ul>/g);
                if (ulMatches) {
                    ulCount++;
                }
            }
        }

        console.log(`  content 필드 있는 문서: ${hasContentField}개`);
        console.log(`  깨진 밑줄 태그: ${brokenCount}개`);
        console.log(`  </ul> 포함 문서: ${ulCount}개`);
    }
}

verify()
    .then(() => { console.log('\n검증 완료'); process.exit(0); })
    .catch(err => { console.error('검증 실패:', err); process.exit(1); });
