import crypto from "node:crypto";
import path from "node:path";
import { isoNow, writeYamlDocument } from "./review-artifact-utils.js";
function safeReasonCode(reasonCode) {
    const normalized = reasonCode
        .trim()
        .toLowerCase()
        .replace(/[^a-z0-9_-]+/g, "-")
        .replace(/^-+|-+$/g, "");
    return normalized.length > 0 ? normalized : "failure";
}
export class ReviewStructuredFailureError extends Error {
    failureRecord;
    failureRecordPath;
    constructor(args) {
        super(args.failureRecord.human_message);
        this.name = "ReviewStructuredFailureError";
        this.failureRecord = args.failureRecord;
        this.failureRecordPath = args.failureRecordPath ?? null;
    }
}
export function createStructuredFailureRecord(params) {
    const failureId = `${safeReasonCode(params.reasonCode)}-${crypto
        .randomBytes(4)
        .toString("hex")}`;
    return {
        schema_version: "1",
        failure_id: failureId,
        created_at: isoNow(),
        phase: params.phase,
        reason_code: params.reasonCode,
        human_message: params.humanMessage,
        required_user_action: params.requiredUserAction,
        retry_safety: params.retrySafety,
        artifact_trust: params.artifactTrust,
        dispatch_state: params.dispatchState,
        artifact_refs: params.artifactRefs ?? {},
        mcp_error_code: params.mcpErrorCode,
        details_kind: params.detailsKind,
        details: params.details,
    };
}
export async function writeStructuredFailureRecord(params) {
    const failureRecord = createStructuredFailureRecord(params);
    const failureRecordPath = path.join(params.sessionRoot, "failures", `${failureRecord.failure_id}.yaml`);
    await writeYamlDocument(failureRecordPath, failureRecord);
    return failureRecordPath;
}
export async function writeAndThrowStructuredFailureRecord(params) {
    const failureRecord = createStructuredFailureRecord(params);
    const failureRecordPath = path.join(params.sessionRoot, "failures", `${failureRecord.failure_id}.yaml`);
    await writeYamlDocument(failureRecordPath, failureRecord);
    throw new ReviewStructuredFailureError({
        failureRecord,
        failureRecordPath,
    });
}
