/**
 * 独立执行审批意见字段升级脚本
 * 
 * 用于对备份还原的 forms 库执行 yijianlan 等审批意见字段转换，
 * 作为公式扫描的前置步骤，排除已知的老版本审批意见公式干扰。
 * 
 * 用法：
 *   FORMULA_SCAN_MONGO_URL=mongodb://127.0.0.1:27017/<dbname> \
 *   node main/default/test/run_approval_comments_upgrade.js
 * 
 * 可选参数：
 *   DRY_RUN=true   只统计不修改数据库
 */
'use strict';

const { _helpers: { matchesApprovalPattern, transformField, processFieldsArray, processAmisSchema } } = require('../../../src/rests/migrateApprovalCommentsField');

async function main() {
    const mongoUrl = process.env.FORMULA_SCAN_MONGO_URL || process.env.MONGO_URL;
    if (!mongoUrl) {
        console.error('错误：请设置环境变量 FORMULA_SCAN_MONGO_URL 或 MONGO_URL');
        process.exit(1);
    }

    const dryRun = process.env.DRY_RUN === 'true';

    const MongoClient = require('mongodb').MongoClient;
    const client = new MongoClient(mongoUrl);
    await client.connect();

    const dbName = mongoUrl.split('/').pop().split('?')[0];
    const db = client.db(dbName);
    const formsCollection = db.collection('forms');

    // 不限制 state，扫描所有表单（备份库可能缺少 state 字段）
    const cursor = formsCollection.find({});
    
    let totalForms = 0;
    let totalFields = 0;
    let scannedForms = 0;
    const bulkOps = [];

    while (await cursor.hasNext()) {
        const form = await cursor.next();
        scannedForms++;
        let formUpdated = false;
        const formUpdate = {};
        const formUnset = {};
        let formFieldCount = 0;

        // current.fields
        if (form.current && Array.isArray(form.current.fields)) {
            const { updates, unsets } = processFieldsArray(form.current.fields, 'current.fields');
            if (updates.length > 0) {
                formUpdated = true;
                formFieldCount += updates.length;
                for (const u of updates) {
                    for (const key in u.update) {
                        formUpdate[`${u.path}.${key}`] = u.update[key];
                    }
                }
                for (const p of unsets) {
                    formUnset[p] = '';
                }
            }
        }

        // historys[].fields
        if (Array.isArray(form.historys)) {
            for (let h = 0; h < form.historys.length; h++) {
                const history = form.historys[h];
                if (Array.isArray(history.fields)) {
                    const { updates, unsets } = processFieldsArray(history.fields, `historys.${h}.fields`);
                    if (updates.length > 0) {
                        formUpdated = true;
                        formFieldCount += updates.length;
                        for (const u of updates) {
                            for (const key in u.update) {
                                formUpdate[`${u.path}.${key}`] = u.update[key];
                            }
                        }
                        for (const p of unsets) {
                            formUnset[p] = '';
                        }
                    }
                }
            }
        }

        // amis_schema
        if (form.amis_schema && typeof form.amis_schema === 'string') {
            const transformed = processAmisSchema(form.amis_schema);
            if (transformed) {
                formUpdated = true;
                formUpdate.__approval_comments_original__amis_schema = form.amis_schema;
                formUpdate.amis_schema = transformed;
            }
        }

        if (formUpdated) {
            totalForms++;
            totalFields += formFieldCount;
            if (!dryRun) {
                const updateDoc = { $set: formUpdate };
                if (Object.keys(formUnset).length > 0) {
                    updateDoc.$unset = formUnset;
                }
                bulkOps.push({
                    updateOne: { filter: { _id: form._id }, update: updateDoc }
                });
                if (bulkOps.length >= 500) {
                    await formsCollection.bulkWrite(bulkOps, { ordered: false });
                    bulkOps.length = 0;
                }
            }
        }
    }

    if (!dryRun && bulkOps.length > 0) {
        await formsCollection.bulkWrite(bulkOps, { ordered: false });
    }

    await client.close();

    console.log('');
    console.log(dryRun ? '审批意见字段升级（DRY RUN，未修改数据库）' : '审批意见字段升级完成');
    console.log(`扫描表单数: ${scannedForms}`);
    console.log(`升级表单数: ${totalForms}`);
    console.log(`升级字段数: ${totalFields}`);
}

main().catch(err => {
    console.error('执行失败:', err.message);
    process.exit(1);
});
