/**
 * SmartFollow 视图在运行态不应消费的字段 key。
 * persist 阶段在此基础上还会额外裁剪 aiConfig / aiColumns / formulaConfig。
 */
const SMART_FOLLOW_RUNTIME_OVERRIDES = {
    filter: [],
    sort: [],
};
const SMART_FOLLOW_PERSIST_STRIP_KEYS = [
    'group',
    'aggregate',
    'colorFill',
    'aiConfig',
    'aiColumns',
    'formulaConfig',
    'filter',
    'sort',
];
function isSmartFollow(viewConfig) {
    return viewConfig.type === 'SmartFollow';
}
function dedupeColumnOrder(columnOrder) {
    if (!Array.isArray(columnOrder)) {
        return columnOrder;
    }
    const seen = new Set();
    return columnOrder.filter((id) => {
        if (!id || seen.has(id))
            return false;
        seen.add(id);
        return true;
    });
}
function isSameColumnOrder(origin, deduped) {
    if (origin === deduped)
        return true;
    if (!Array.isArray(origin) || !Array.isArray(deduped)) {
        return origin === deduped;
    }
    if (origin.length !== deduped.length) {
        return false;
    }
    for (let i = 0; i < origin.length; i += 1) {
        if (origin[i] !== deduped[i]) {
            return false;
        }
    }
    return true;
}
/**
 * 加载后内存态规范化：清理 SmartFollow 的 filter/sort 等运行时无效字段。
 * Grid / Task 视图原样返回。
 */
export function normalizeViewConfigForRuntime(viewConfig) {
    const dedupedColumnOrder = dedupeColumnOrder(viewConfig.columnOrder);
    if (!isSmartFollow(viewConfig)) {
        if (isSameColumnOrder(viewConfig.columnOrder, dedupedColumnOrder)) {
            return viewConfig;
        }
        return { ...viewConfig, columnOrder: dedupedColumnOrder };
    }
    return {
        ...viewConfig,
        ...SMART_FOLLOW_RUNTIME_OVERRIDES,
        columnOrder: dedupedColumnOrder,
    };
}
/**
 * 保存前裁剪：在 runtime 归一化基础上，进一步删除 SmartFollow 不消费的持久化字段。
 * Grid / Task 视图原样返回。
 */
export function normalizeViewConfigForPersist(viewConfig) {
    const dedupedColumnOrder = dedupeColumnOrder(viewConfig.columnOrder);
    if (!isSmartFollow(viewConfig)) {
        if (isSameColumnOrder(viewConfig.columnOrder, dedupedColumnOrder)) {
            return viewConfig;
        }
        return { ...viewConfig, columnOrder: dedupedColumnOrder };
    }
    const cleaned = { ...viewConfig };
    for (const key of SMART_FOLLOW_PERSIST_STRIP_KEYS) {
        delete cleaned[key];
    }
    return {
        ...cleaned,
        columnOrder: dedupedColumnOrder,
    };
}
