"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createUsageCommandRepairEvidence = createUsageCommandRepairEvidence;
exports.classifyEnvironmentExecutionFailure = classifyEnvironmentExecutionFailure;
exports.createEnvironmentExecutionError = createEnvironmentExecutionError;
__exportStar(require("./errors/index"), exports);
const index_1 = require("./errors/index");
const command_repair_1 = require("./output/command-repair");
function createUsageCommandRepairEvidence(rejectedArgv, repositoryRoot) {
    try {
        const commandRepair = (0, command_repair_1.repairCommandArgv)(rejectedArgv, { repositoryRoot });
        if (commandRepair.candidateCount === 0 || commandRepair.confidence === "low") {
            return undefined;
        }
        const hasActionableRepair = commandRepair.candidates.some((candidate) => candidate.rejectedTokens.length > 0
            || candidate.edits.some((edit) => edit.kind !== "move"));
        if (!hasActionableRepair) {
            return undefined;
        }
        return { commandRepair };
    }
    catch {
        return undefined;
    }
}
/**
 * Classifies failures that occur before a child process returns an exit status.
 * These are host/execution-boundary failures, not validation results.
 */
function classifyEnvironmentExecutionFailure(error, commandArgv) {
    const candidate = error instanceof Error
        ? error
        : null;
    const message = candidate?.message ?? String(error);
    const explicitCode = typeof candidate?.code === "string" ? candidate.code.toUpperCase() : null;
    const embeddedCode = message.match(/\b(EACCES|EPERM|ENOENT)\b/u)?.[1] ?? null;
    const systemCode = explicitCode ?? embeddedCode;
    const reason = systemCode === "EACCES" || systemCode === "EPERM"
        ? "permission-restricted"
        : systemCode === "ENOENT"
            ? "executable-unavailable"
            : "spawn-failed";
    return {
        classification: "environment-execution",
        reason,
        systemCode,
        message,
        commandArgv: [...commandArgv],
        retryOutsideRestriction: reason === "permission-restricted"
    };
}
function createEnvironmentExecutionError(failure) {
    const permissionRestricted = failure.reason === "permission-restricted";
    const exitCode = permissionRestricted
        ? index_1.RuntimeExitCode.PERMISSION_FAILURE
        : index_1.RuntimeExitCode.UNAVAILABLE_DEPENDENCY;
    const code = permissionRestricted
        ? "VALIDATION_ENVIRONMENT_EXECUTION_RESTRICTED"
        : "VALIDATION_ENVIRONMENT_EXECUTION_UNAVAILABLE";
    const retryGuidance = failure.retryOutsideRestriction
        ? "The exact underlying command may be retried outside the reported host restriction after confirming that the alternate environment is authorized."
        : "Do not treat this as a validation result; make the executable environment available, then explicitly retry the exact command.";
    return new index_1.RuntimeError({
        message: "Command-owned validation could not start in the current execution environment.",
        code,
        exitCode,
        writeOutcome: "no-writes",
        details: [
            `classification: ${failure.classification}`,
            `reason: ${failure.reason}`,
            `systemCode: ${failure.systemCode ?? "unknown"}`,
            `commandArgv: ${JSON.stringify(failure.commandArgv)}`,
            failure.message,
            "No validation result was recorded because the child process did not produce an exit status.",
            `retryOutsideRestriction: ${failure.retryOutsideRestriction}`,
            retryGuidance
        ],
        findings: [{
                code,
                severity: "error",
                message: "The command-owned validation child process did not start.",
                reason: failure.reason,
                noWriteBoundary: "Environment-execution failures do not append validation evidence."
            }],
        recoveryActions: [(0, index_1.createNonCallableRecoveryAction)({
                id: permissionRestricted
                    ? "recovery.validation.retry-outside-environment-restriction"
                    : "recovery.validation.restore-execution-environment",
                command: "task validation-record",
                explanation: retryGuidance,
                reason: "The shared boundary cannot select or authorize a different execution host, and the original validation-record inputs must remain exact."
            })],
        cause: failure
    });
}
