/*
 * 文件定位：Agent 运行态实现层 / 自修复面。
 * 核心目的：承载 repair Strategy Registry 这一能力位点。
 * 能力要求1：需要把文件名表达的能力落实成清晰的类型、输入输出和最小行为。
 * 能力要求2：如果后续发现语义不足，应优先补接口契约，而不是把逻辑散落到相邻文件。
 * 边界：承托和治理运行态，不吞并执行引擎、模型适配器或官方模块内部实现。
 * 对接：需要服务 applicationSurface、officialModuleSurface、governancePlane、invocationMethod 和 inspection/debug 等运行面。
 * 实现提示：先补稳定类型契约、最小可测行为和清晰错误边界，再接入真实执行逻辑。
 */
export const runtimeRepairStrategyRegistryDescriptor = {
    surface: "runtime.selfRepair",
    capability: "repairStrategyRegistry",
    purpose: "register and query dry-run self-repair strategies without executing repair actions",
    unsafeSideEffects: false,
};
function hasText(value) {
    return typeof value === "string" && value.trim().length > 0;
}
function cleanList(values) {
    return [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))];
}
function failure(code, message, boundary) {
    return {
        ok: false,
        error: {
            code,
            message,
            boundary,
            safeForRuntimeInspection: true,
            internalDetailExposed: false,
        },
        events: ["runtime.selfRepair.repairStrategyRegistry.rejected"],
    };
}
function normalizeStrategy(definition) {
    if (!hasText(definition.strategyId) || !hasText(definition.kind)) {
        return undefined;
    }
    const kind = definition.kind.trim();
    return {
        strategyId: definition.strategyId.trim(),
        kind,
        summary: definition.summary?.trim() || `${kind} self-repair strategy`,
        supportedFaultCategories: cleanList(definition.supportedFaultCategories),
        risk: definition.risk ?? "low",
        requiresApproval: definition.requiresApproval ?? definition.risk === "high",
        ownerSurface: definition.ownerSurface?.trim() || "runtime",
        tags: cleanList(definition.tags),
        dryRunOnly: true,
        unsafeSideEffects: false,
    };
}
function matchesQuery(strategy, query) {
    if (query === undefined) {
        return true;
    }
    if (hasText(query.strategyId) && strategy.strategyId !== query.strategyId.trim()) {
        return false;
    }
    if (hasText(query.kind) && strategy.kind !== query.kind.trim()) {
        return false;
    }
    if (query.faultCategory !== undefined && !strategy.supportedFaultCategories.includes(query.faultCategory)) {
        return false;
    }
    const queryTags = cleanList(query.tags);
    if (queryTags.length > 0 && !queryTags.every((tag) => strategy.tags.includes(tag))) {
        return false;
    }
    return true;
}
export function createRepairStrategyRegistry(request) {
    if (request === undefined || !hasText(request.runtimeId)) {
        return failure("MISSING_RUNTIME_ID", "repair strategy registry requires a runtimeId", "input");
    }
    if (request.strategies === undefined || request.strategies.length === 0) {
        return failure("MISSING_STRATEGIES", "repair strategy registry requires at least one strategy", "input");
    }
    if (request.runtimeReady === false) {
        return failure("RUNTIME_NOT_READY", "repair strategies can only be registered through a ready runtime host", "runtime-state");
    }
    if (request.contract?.accepted === false) {
        return failure("CONTRACT_REJECTED", request.contract.reason ?? "repair strategy registry was rejected by contract surface", "contract");
    }
    if (request.governance?.accepted === false) {
        return failure("GOVERNANCE_REJECTED", request.governance.reason ?? "repair strategy registry was rejected by governance", "governance");
    }
    const allowedStrategyKinds = cleanList(request.allowedStrategyKinds);
    const strategies = [];
    const seen = new Set();
    for (const definition of request.strategies) {
        if (!hasText(definition.strategyId)) {
            return failure("MISSING_STRATEGY_ID", "each repair strategy requires a stable strategyId", "input");
        }
        if (!hasText(definition.kind)) {
            return failure("MISSING_STRATEGY_KIND", "each repair strategy requires a strategy kind", "input");
        }
        const strategy = normalizeStrategy(definition);
        if (strategy === undefined) {
            return failure("MISSING_STRATEGY_KIND", "repair strategy could not be normalized", "input");
        }
        if (seen.has(strategy.strategyId)) {
            return failure("DUPLICATE_STRATEGY_ID", `repair strategy ${strategy.strategyId} is already registered`, "registry");
        }
        if (allowedStrategyKinds.length > 0 && !allowedStrategyKinds.includes(strategy.kind)) {
            return failure("STRATEGY_SCOPE_DENIED", `repair strategy ${strategy.kind} is outside the allowed scope`, "scope");
        }
        seen.add(strategy.strategyId);
        strategies.push(strategy);
    }
    const matchedStrategies = strategies.filter((strategy) => matchesQuery(strategy, request.query));
    return {
        ok: true,
        registry: {
            runtimeId: request.runtimeId.trim(),
            strategies,
            matchedStrategies,
            strategyCount: strategies.length,
            matchedCount: matchedStrategies.length,
            audit: {
                dryRun: true,
                unsafeSideEffects: false,
                registry: "runtime.selfRepair.repairStrategyRegistry",
                contractChecked: true,
                governanceChecked: true,
            },
        },
        events: ["runtime.selfRepair.repairStrategyRegistry.ready"],
    };
}
