/**
 * Knowledge Asset Migration — 问题五十七核心机制之五。
 *
 * 管理知识资产 schema 变更时的迁移策略:
 * - Migration dry-run（预览影响）
 * - 兼容性报告
 * - 用户修改保护
 * - 迁移优先级（P0→P1→P2→P3）
 */
import { recordConsumptionTrace, CONSUMER_FIELD_CONTRACTS } from "../templates/consumption_trace_store.js";
/** 迁移优先级排序 */
const MIGRATION_PRIORITY = {
    hard_rule: 0,
    workflow: 1,
    procedure: 2,
    pipeline: 3,
    review_rule: 4,
    checklist: 5,
    pattern: 6,
    artifact_template: 7,
    domain_knowledge: 8,
    product_profile: 9,
};
// ── 核心函数 ──
/**
 * 规划知识资产迁移。
 */
export function planKnowledgeAssetMigration(params) {
    const planId = `ka-migration-${Date.now()}`;
    const steps = [];
    const affected = params.assets.filter((a) => needsMigration(a.frontmatter, params.schema_changes));
    // 按优先级分组
    const byKind = new Map();
    for (const asset of affected) {
        const kind = asset.frontmatter.asset_kind ?? "domain_knowledge";
        const group = byKind.get(kind) ?? [];
        group.push(asset);
        byKind.set(kind, group);
    }
    // 生成步骤
    const sortedKinds = [...byKind.keys()].sort((a, b) => (MIGRATION_PRIORITY[a] ?? 9) - (MIGRATION_PRIORITY[b] ?? 9));
    for (const kind of sortedKinds) {
        const assets = byKind.get(kind) ?? [];
        steps.push({
            priority: MIGRATION_PRIORITY[kind] <= 1 ? "P0" : MIGRATION_PRIORITY[kind] <= 4 ? "P1" : MIGRATION_PRIORITY[kind] <= 7 ? "P2" : "P3",
            description_zh: `迁移 ${assets.length} 个 ${kind} 资产`,
            asset_kinds: [kind],
            asset_count: assets.length,
            automated: MIGRATION_PRIORITY[kind] <= 7,
            requires_user_confirmation: MIGRATION_PRIORITY[kind] <= 1,
        });
    }
    // 全量五字段硬契约校验 — 所有 affected assets 缺字段都进入 hard_fail_findings
    const hardFailFindings = [];
    let traceCount = 0;
    for (const asset of affected) {
        const fm = asset.frontmatter;
        const invalidFields = [];
        if (fm.version === undefined || fm.version === "")
            invalidFields.push("version");
        if (fm.schema === undefined || fm.schema === "")
            invalidFields.push("schema");
        if (fm.hash === undefined || fm.hash === "")
            invalidFields.push("hash");
        if (fm.user_modified === undefined || typeof fm.user_modified !== "boolean")
            invalidFields.push("user_modified");
        if (fm.migration_note === undefined || fm.migration_note === "")
            invalidFields.push("migration_note");
        if (invalidFields.length > 0) {
            hardFailFindings.push({
                asset_id: fm.id ?? "unknown",
                invalid_fields: invalidFields,
                reason_zh: `资产 ${fm.id ?? "unknown"} 五字段硬契约失败: ${invalidFields.join(", ")}`,
            });
            continue;
        }
        // trace 限量避免噪声，但 hard_fail 校验不限量
        if (traceCount < 5) {
            recordConsumptionTrace({
                consumer: "sync_migration",
                asset_id: fm.id ?? "unknown",
                fields_consumed: CONSUMER_FIELD_CONTRACTS.sync_migration,
                matched_reason: `migration v=${fm.version} schema=${fm.schema} hash=${fm.hash} user_modified=${fm.user_modified} note=${fm.migration_note}`,
                task_id_or_route: planId,
                consumed_at: new Date().toISOString(),
            });
            traceCount++;
        }
    }
    return {
        plan_id: planId,
        created_at: new Date().toISOString(),
        source_schema_version: params.source_version,
        target_schema_version: params.target_version,
        affected_assets: affected.map((a) => a.frontmatter.id ?? "unknown"),
        migration_steps: steps,
        hard_fail_findings: hardFailFindings,
    };
}
/**
 * 判断资产是否需要迁移。
 */
function needsMigration(fm, changes) {
    for (const change of changes) {
        if (change.change_type === "added_required") {
            if (fm[change.field] === undefined)
                return true;
        }
        if (change.change_type === "renamed" || change.change_type === "deprecated") {
            if (fm[change.field] !== undefined)
                return true;
        }
    }
    return false;
}
/**
 * 执行迁移 dry-run — 不修改任何文件，只预览影响。
 */
export function runMigrationDryRun(params) {
    const details = [];
    let toMigrate = 0;
    let breaking = 0;
    for (const asset of params.assets) {
        const id = asset.frontmatter.id ?? "unknown";
        const changes = [];
        let isBreaking = false;
        // 跳过用户修改的资产
        if (params.user_modified_assets.includes(id)) {
            details.push({ asset_id: id, will_change: false, changes: ["用户已修改，跳过"], breaking: false });
            continue;
        }
        for (const change of params.schema_changes) {
            if (change.change_type === "added_required") {
                if (asset.frontmatter[change.field] === undefined) {
                    changes.push(`需添加字段: ${change.field}`);
                    toMigrate++;
                    isBreaking = true;
                }
            }
            if (change.change_type === "deprecated") {
                if (asset.frontmatter[change.field] !== undefined) {
                    changes.push(`字段将废弃: ${change.field}`);
                    toMigrate++;
                }
            }
        }
        if (changes.length > 0) {
            if (isBreaking)
                breaking++;
            details.push({ asset_id: id, will_change: true, changes, breaking: isBreaking });
        }
        else {
            details.push({ asset_id: id, will_change: false, changes: [], breaking: false });
        }
    }
    return {
        total_assets: params.assets.length,
        assets_to_migrate: toMigrate,
        assets_unchanged: params.assets.length - toMigrate - params.user_modified_assets.length,
        assets_skipped: params.user_modified_assets.length,
        assets_with_conflicts: 0,
        estimated_breaking_changes: breaking,
        per_asset_details: details,
    };
}
/**
 * 生成兼容性报告。
 */
export function generateCompatibilityReport(params) {
    const breaking = params.schema_changes
        .filter((c) => c.change_type === "added_required" || c.change_type === "removed")
        .map((c) => `${c.change_type}: ${c.field}`);
    const compatible = params.schema_changes
        .filter((c) => c.change_type === "type_changed" || c.change_type === "deprecated")
        .map((c) => `${c.change_type}: ${c.field}`);
    const deprecated = params.schema_changes
        .filter((c) => c.change_type === "deprecated")
        .map((c) => c.field);
    const newRequired = params.schema_changes
        .filter((c) => c.change_type === "added_required")
        .map((c) => c.field);
    return {
        source_version: params.source_version,
        target_version: params.target_version,
        breaking_changes: breaking,
        compatible_changes: compatible,
        deprecated_fields: deprecated,
        new_required_fields: newRequired,
        migration_required: breaking.length > 0,
    };
}
/**
 * 检查用户修改的资产是否会被迁移覆盖。
 */
export function checkUserModificationProtection(asset_id, user_modified_assets, migration_plan) {
    if (user_modified_assets.includes(asset_id) && migration_plan.affected_assets.includes(asset_id)) {
        return {
            protected: true,
            reason_zh: `资产 ${asset_id} 已被用户修改，迁移时跳过，需人工确认后迁移`,
        };
    }
    return { protected: false, reason_zh: "资产未被用户修改，可安全迁移" };
}
//# sourceMappingURL=knowledge_asset_migration.js.map