/*
 * 文件定位：Agent 运行态实现层 / 运行检查面。
 * 核心目的：承载 runtime Inspector 这一能力位点。
 * 能力要求1：需要把文件名表达的能力落实成清晰的类型、输入输出和最小行为。
 * 能力要求2：如果后续发现语义不足，应优先补接口契约，而不是把逻辑散落到相邻文件。
 * 边界：承托和治理运行态，不吞并执行引擎、模型适配器或官方模块内部实现。
 * 对接：需要服务 applicationSurface、officialModuleSurface、governancePlane、invocationMethod 和 inspection/debug 等运行面。
 * 实现提示：先补稳定类型契约、最小可测行为和清晰错误边界，再接入真实执行逻辑。
 */
export function isRuntimeInspectionBlank(value) {
    return typeof value !== "string" || value.trim().length === 0;
}
export function cleanRuntimeInspectionList(values) {
    return [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))];
}
export function runtimeInspectionError(code, message, boundary) {
    return {
        code,
        message,
        boundary,
        safeForApplication: true,
        internalDetailExposed: false,
    };
}
export function rejectRuntimeInspection(code, message, boundary, event = "runtime.inspection.rejected") {
    return {
        ok: false,
        error: runtimeInspectionError(code, message, boundary),
        events: [event],
    };
}
function normalizeSurfaceSignals(surfaces) {
    if (surfaces === undefined) {
        return [];
    }
    if (Array.isArray(surfaces)) {
        return surfaces;
    }
    return Object.entries(surfaces).map(([surfaceId, ready]) => ({
        signalId: surfaceId,
        boundary: "surface",
        ready,
    }));
}
function signalId(signal, fallbackPrefix, index) {
    return isRuntimeInspectionBlank(signal.signalId) ? `${fallbackPrefix}:${index}` : (signal.signalId ?? "").trim();
}
function signalFindings(signal, fallbackPrefix, index) {
    if (signal.findings !== undefined && signal.findings.length > 0) {
        return signal.findings;
    }
    if (signal.ready === false) {
        const id = signalId(signal, fallbackPrefix, index);
        const boundary = signal.boundary ?? "surface";
        return [
            {
                findingId: `${id}.not-ready`,
                severity: "error",
                boundary,
                message: `runtime inspection signal is not ready: ${id}`,
                relatedSurface: id,
            },
        ];
    }
    return [];
}
function collectSignals(signals, fallbackPrefix) {
    const ids = [];
    const findings = [];
    const events = [];
    signals.forEach((signal, index) => {
        ids.push(signalId(signal, fallbackPrefix, index));
        findings.push(...signalFindings(signal, fallbackPrefix, index));
        events.push(...(signal.events ?? []));
    });
    return { ids, findings, events };
}
function statusFromFindings(findings) {
    if (findings.some((finding) => finding.severity === "error")) {
        return "blocked";
    }
    if (findings.some((finding) => finding.severity === "warning")) {
        return "degraded";
    }
    return "ready";
}
export function inspectRuntime(request = {}) {
    if (isRuntimeInspectionBlank(request.runtimeId)) {
        return rejectRuntimeInspection("MISSING_RUNTIME_ID", "runtime inspector requires a runtimeId", "input", "runtime.inspection.rejected");
    }
    if (request.runtimeReady === false) {
        return rejectRuntimeInspection("RUNTIME_NOT_READY", "runtime inspector can only inspect a ready runtime surface", "runtime-state", "runtime.inspection.rejected");
    }
    if (request.contract?.accepted === false) {
        return rejectRuntimeInspection("CONTRACT_REJECTED", request.contract.reason ?? "runtime inspection was rejected by contract surface", "contract", "runtime.inspection.rejected");
    }
    if (request.governance?.accepted === false) {
        return rejectRuntimeInspection("GOVERNANCE_REJECTED", request.governance.reason ?? "runtime inspection was rejected by governance", "governance", "runtime.inspection.rejected");
    }
    const surfaceSignals = collectSignals(normalizeSurfaceSignals(request.surfaces), "surface");
    const moduleSignals = collectSignals(request.modules ?? [], "module");
    const invariantSignals = collectSignals(request.invariants ?? [], "invariant");
    const findings = [...surfaceSignals.findings, ...moduleSignals.findings, ...invariantSignals.findings];
    const status = statusFromFindings(findings);
    return {
        ok: true,
        snapshot: {
            runtimeId: (request.runtimeId ?? "").trim(),
            status,
            audience: request.audience,
            findings,
            checkedSurfaces: surfaceSignals.ids,
            checkedModules: moduleSignals.ids,
            checkedInvariants: invariantSignals.ids,
            inspectionSurface: "runtime.inspection.runtimeInspector",
            governanceChecked: true,
            contractChecked: true,
            unsafeSideEffects: false,
        },
        events: [
            `runtime.inspection.${status}`,
            ...surfaceSignals.events,
            ...moduleSignals.events,
            ...invariantSignals.events,
        ],
    };
}
