"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FieldOrchestrator = void 0;
const i18n_1 = __importDefault(require("../../../../locales/i18n.js"));
/**
 * FieldOrchestrator —— 统一编排字段创建、编辑、删除流程
 *
 * orchestrator 不感知具体字段类型，所有分支由 driver 内部实现。
 * 所有方法返回 FieldActionResult，调用方据此决定 UI 行为（如是否关闭面板）。
 *
 * **createField 完整流程：**
 *   1. 从 registry 查找 driver（找不到直接报错）
 *   2. driver.validateConfig —— 配置校验
 *   3. driver.persistMeta   —— 持久化元数据（AI 远程 / 公式本地）
 *   4. driver.buildColumnDef —— 构建列定义并 addColumn
 *   5. driver.attachToView   —— 挂载到视图（更新 columnOrder、rawData 空值等）
 *   6. store.setFieldRecord  —— 双写旧分桶（向后兼容）
 *   7. runtime.materialize   —— 物化数据（公式批量计算 / AI 批量提交 / 普通 noop）
 *   8. arms 埋点 + eventBus 通知
 *
 * **editField / deleteField** 流程类似，详见各方法注释。
 */
const arms_hot_tag_log_1 = require("../../../../utils/arms/arms-hot-tag-log.js");
class FieldOrchestrator {
    constructor(registry, store, runtime) {
        this.registry = registry;
        this.store = store;
        this.runtime = runtime;
    }
    /**
     * 创建字段的统一流程。
     *
     * @param type      - 字段类型标识（如 'ai-generate' / 'formula'）
     * @param config    - 字段配置，结构由对应 driver 定义
     * @param ctx       - 字段上下文
     * @param callbacks - 可选的成功/失败回调（便于调用方处理 UI 侧逻辑）
     * @returns FieldActionResult，成功时携带 record，失败时携带 error
     */
    async createField(type, config, ctx, callbacks) {
        var _a, _b, _c, _d;
        const driver = this.registry.get(type);
        if (!driver) {
            const err = new Error(`[FieldOrchestrator] unknown field type: "${type}"`);
            (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onError) === null || _a === void 0 ? void 0 : _a.call(callbacks, err);
            return { success: false, error: err };
        }
        try {
            const validation = driver.validateConfig(config);
            if (!validation.valid) {
                const err = new Error(validation.error || 'Invalid field config');
                (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onError) === null || _b === void 0 ? void 0 : _b.call(callbacks, err);
                return { success: false, error: err };
            }
            const record = await driver.persistMeta(config, ctx);
            driver.buildColumnDef(record, ctx);
            driver.attachToView(record, ctx);
            this.store.setFieldRecord(record.id, record, ctx.dataModel);
            await this.runtime.materialize(driver, record, config, ctx);
            (0, arms_hot_tag_log_1.armsHottagLog)({
                hottag: 'cn-ai-table.field-system.createField',
                name: i18n_1.default.get({ id: 'CreateField', dm: '创建字段' }),
                c6: type,
                c8: record.id,
            });
            ctx.eventBus.emit(ctx.cnAiListEventNames.AI_FIELD_ADDED, {
                viewId: ctx.viewId,
                columnCode: record.id,
            });
            (_c = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onSuccess) === null || _c === void 0 ? void 0 : _c.call(callbacks);
            return { success: true, record };
        }
        catch (error) {
            console.error('[FieldOrchestrator] createField failed:', error);
            (_d = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onError) === null || _d === void 0 ? void 0 : _d.call(callbacks, error);
            return { success: false, error };
        }
    }
    /**
     * 编辑字段的统一流程。
     * 优先调用 driver.updateMeta（编辑专属逻辑），若未实现则退化到 persistMeta。
     * 编辑完成后重新写入 store 并触发物化（如公式重新计算）。
     */
    async editField(type, columnId, config, ctx, callbacks) {
        var _a, _b, _c, _d;
        const driver = this.registry.get(type);
        if (!driver) {
            const err = new Error(`[FieldOrchestrator] unknown field type: "${type}"`);
            (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onError) === null || _a === void 0 ? void 0 : _a.call(callbacks, err);
            return { success: false, error: err };
        }
        try {
            const validation = driver.validateConfig(config);
            if (!validation.valid) {
                const err = new Error(validation.error || 'Invalid field config');
                (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onError) === null || _b === void 0 ? void 0 : _b.call(callbacks, err);
                return { success: false, error: err };
            }
            let record;
            if (driver.updateMeta) {
                record = await driver.updateMeta(columnId, config, ctx);
            }
            else {
                record = await driver.persistMeta(config, ctx);
            }
            this.store.setFieldRecord(record.id, record, ctx.dataModel);
            await this.runtime.materialize(driver, record, config, ctx);
            (0, arms_hot_tag_log_1.armsHottagLog)({
                hottag: 'cn-ai-table.field-system.editField',
                name: 'editField',
                c6: type,
                c8: columnId,
            });
            (_c = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onSuccess) === null || _c === void 0 ? void 0 : _c.call(callbacks);
            return { success: true, record };
        }
        catch (error) {
            console.error('[FieldOrchestrator] editField failed:', error);
            (_d = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onError) === null || _d === void 0 ? void 0 : _d.call(callbacks, error);
            return { success: false, error };
        }
    }
    /**
     * 删除字段的统一流程。
     * 先调用 driver.remove（AI 字段需远程删除），再从 store 清理本地记录。
     */
    async deleteField(type, columnId, ctx, callbacks) {
        var _a, _b, _c;
        const driver = this.registry.get(type);
        if (!driver) {
            const err = new Error(`[FieldOrchestrator] unknown field type: "${type}"`);
            (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onError) === null || _a === void 0 ? void 0 : _a.call(callbacks, err);
            return { success: false, error: err };
        }
        try {
            await driver.remove(columnId, ctx);
            this.store.removeFieldRecord(columnId, ctx.dataModel);
            (0, arms_hot_tag_log_1.armsHottagLog)({
                hottag: 'cn-ai-table.field-system.deleteField',
                name: 'deleteField',
                c6: type,
                c8: columnId,
            });
            (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onSuccess) === null || _b === void 0 ? void 0 : _b.call(callbacks);
            return { success: true };
        }
        catch (error) {
            console.error('[FieldOrchestrator] deleteField failed:', error);
            (_c = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onError) === null || _c === void 0 ? void 0 : _c.call(callbacks, error);
            return { success: false, error };
        }
    }
    /**
     * 获取字段编辑所需的配置信息。
     * 优先通过 driver.hydrate 从旧数据结构恢复，退化到 store.getFieldRecord。
     */
    getEditConfig(type, columnId, ctx) {
        const driver = this.registry.get(type);
        if (!driver)
            return undefined;
        if (driver.hydrate) {
            return driver.hydrate(columnId, ctx);
        }
        return this.store.getFieldRecord(columnId, ctx.dataModel);
    }
}
exports.FieldOrchestrator = FieldOrchestrator;
