/**
 * TODO: 已设计但未接入运行时的治理机制。待治理管线完善后启用。
 *
 * 契约状态覆盖存储 — 持久化人工确认的契约状态变更。
 *
 * 问题二十核心规则:
 * - enforced 降级/禁用必须人工确认
 * - draft/advisory/experimental 不得自动晋级 enforced
 * - deprecated/removed 状态更新必须记录 replacement 或 migration note
 * - 持久化审计记录，不能只改内存
 * - 状态变更必须有 evidence_refs + human confirmation
 */
import fs from "node:fs";
import path from "node:path";
import { safeJsonParse } from "../core/helpers.js";
import { getContractById, createContractStateApplier } from "./contract_registry.js";
const applyContractStateOverride = createContractStateApplier();
/** 合法的契约状态转移映射 */
const VALID_CONTRACT_TRANSITIONS = {
    draft: ["advisory", "experimental"],
    advisory: ["enforced", "experimental", "deprecated", "removed"],
    enforced: ["advisory", "deprecated"],
    experimental: ["advisory", "deprecated", "removed"],
    deprecated: ["advisory", "removed"],
    removed: ["experimental"],
};
/**
 * 契约状态存储 — 管理人工确认的契约状态变更
 */
export class ContractStateStore {
    filePath;
    overrides = [];
    loaded = false;
    constructor(stateDir) {
        this.filePath = path.join(stateDir, "contract-state-overrides.json");
        if (!fs.existsSync(stateDir)) {
            fs.mkdirSync(stateDir, { recursive: true });
        }
    }
    ensureLoaded() {
        if (this.loaded)
            return;
        this.loaded = true;
        try {
            const data = fs.readFileSync(this.filePath, "utf-8");
            this.overrides = safeJsonParse(data) ?? [];
        }
        catch {
            this.overrides = [];
        }
    }
    persist() {
        const tmpPath = `${this.filePath}.tmp`;
        fs.writeFileSync(tmpPath, JSON.stringify(this.overrides, null, 2));
        fs.renameSync(tmpPath, this.filePath);
    }
    /** 获取契约的生效状态 */
    getEffectiveState(contractId, defaultState) {
        this.ensureLoaded();
        let latest;
        for (const o of this.overrides) {
            if (o.contract_id === contractId)
                latest = o;
        }
        return latest ? latest.new_state : defaultState;
    }
    /** 列出所有状态覆盖记录 */
    list() {
        this.ensureLoaded();
        return this.overrides.map((o) => ({
            ...o,
            evidence_refs: [...o.evidence_refs],
        }));
    }
    /** 校验契约状态更新请求 */
    validate(request) {
        const errors = [];
        const entry = getContractById(request.contract_id);
        const currentState = entry?.state ?? "draft";
        if (!entry) {
            errors.push(`contract_id ${request.contract_id} 不在 Unified Contract Registry 中`);
        }
        if (request.target_state === currentState) {
            errors.push(`target_state (${request.target_state}) 与当前状态相同，无需变更`);
        }
        if (entry && request.target_state !== currentState) {
            const allowed = VALID_CONTRACT_TRANSITIONS[currentState];
            if (!allowed.includes(request.target_state)) {
                errors.push(`${currentState} → ${request.target_state} 不是合法转移 (允许: ${allowed.join(", ")})`);
            }
        }
        // evidence_refs 必须非空
        if (request.evidence_refs.length === 0) {
            errors.push("状态更新至少需要一个 evidence_ref");
        }
        // 人工确认必须
        if (!request.confirm) {
            errors.push("confirm=true 必须提供；契约状态变更需要人工确认");
        }
        if (!request.confirmed_by.trim()) {
            errors.push("confirmed_by 不能为空");
        }
        if (!request.reason.trim()) {
            errors.push("reason 不能为空");
        }
        // enforced 降级必须人工确认（已由 confirm 检查覆盖，但增加额外说明）
        if (currentState === "enforced" && request.target_state !== "enforced" && !request.confirm) {
            errors.push("enforced 契约降级/禁用必须人工确认");
        }
        // draft/advisory/experimental 不得自动晋级 enforced
        if (request.target_state === "enforced" &&
            (currentState === "draft" || currentState === "advisory" || currentState === "experimental")) {
            // 允许但需要 evidence + confirmation
            if (request.evidence_refs.length === 0) {
                errors.push("晋级到 enforced 需要提供证据");
            }
        }
        // deprecated/removed 必须有 replacement 或 migration_note
        if (request.target_state === "deprecated" &&
            !request.replacement_contract_id &&
            !request.migration_note) {
            errors.push("deprecated 状态更新必须提供 replacement_contract_id 或 migration_note");
        }
        if (request.target_state === "removed" &&
            !request.migration_note) {
            errors.push("removed 状态更新必须提供 migration_note");
        }
        const override = {
            contract_id: request.contract_id,
            previous_state: currentState,
            new_state: request.target_state,
            reason: request.reason,
            evidence_refs: [...request.evidence_refs],
            confirmed_by: request.confirmed_by,
            updated_at: new Date().toISOString(),
            replacement_contract_id: request.replacement_contract_id,
            migration_note: request.migration_note,
        };
        return {
            contract_id: request.contract_id,
            previous_state: currentState,
            new_state: request.target_state,
            updated: false,
            dry_run: request.dry_run,
            validation_errors: errors,
            override: errors.length === 0 ? override : null,
        };
    }
    /** 校验并应用状态更新 */
    apply(request) {
        this.ensureLoaded();
        const result = this.validate(request);
        if (result.validation_errors.length > 0 || request.dry_run || !result.override) {
            return result;
        }
        // 持久化覆盖记录
        this.overrides.push(result.override);
        this.persist();
        // 更新运行时注册表（通过已校验的 override）
        applyContractStateOverride(result.override);
        return { ...result, updated: true };
    }
    /** 清空所有覆盖记录 */
    clear() {
        this.overrides = [];
        this.loaded = true;
        this.persist();
    }
}
//# sourceMappingURL=contract_state_store.js.map