"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderWorkflowOutcomeValue = renderWorkflowOutcomeValue;
exports.coerceCanonicalWorkflowResult = coerceCanonicalWorkflowResult;
exports.coerceCanonicalWorkflowFinalResult = coerceCanonicalWorkflowFinalResult;
const types_1 = require("../../workflows/types");
function renderWorkflowOutcomeValue(outcome, labels) {
    switch (outcome) {
        case "proceed":
            return labels.resultOutcomeProceedLabel;
        case "wait_human":
            return labels.resultOutcomeWaitHumanLabel;
        case "fail":
            return labels.resultOutcomeFailLabel;
    }
}
function coerceCanonicalWorkflowResult(value) {
    if (value === null || value === undefined) {
        return null;
    }
    if (!isRecord(value)) {
        return null;
    }
    if (!hasOnlyRecordKeys(value, WORKFLOW_RESULT_FIELD_NAMES)) {
        return null;
    }
    const result = value;
    const outcome = typeof result.outcome === "string" ? result.outcome : null;
    const resultSummary = typeof result.resultSummary === "string" ? result.resultSummary : null;
    if (outcome === null ||
        resultSummary === null ||
        !isWorkflowResultOutcome(outcome)) {
        return null;
    }
    return (0, types_1.buildWorkflowResultWithDefaults)({
        outcome,
        resultSummary,
        evidence: coerceStringArray(result.evidence),
        humanComment: coerceNullableString(result.humanComment),
    });
}
function coerceCanonicalWorkflowFinalResult(value) {
    const result = coerceCanonicalWorkflowResult(value);
    if (result === null || !isWorkflowFinalResultOutcome(result.outcome)) {
        return null;
    }
    return result;
}
function coerceStringArray(value) {
    if (!Array.isArray(value)) {
        return [];
    }
    return value
        .map((entry) => (typeof entry === "string" ? entry.trim() : ""))
        .filter((entry) => entry.length > 0);
}
function coerceNullableString(value) {
    if (typeof value !== "string") {
        return null;
    }
    const trimmed = value.trim();
    return trimmed.length > 0 ? trimmed : null;
}
function isWorkflowResultOutcome(value) {
    return types_1.WORKFLOW_RESULT_OUTCOMES.includes(value);
}
function isWorkflowFinalResultOutcome(value) {
    return types_1.WORKFLOW_FINAL_RESULT_OUTCOMES.includes(value);
}
const WORKFLOW_RESULT_FIELD_NAMES = new Set([
    "outcome",
    "resultSummary",
    "evidence",
    "humanComment",
]);
function hasOnlyRecordKeys(value, allowedKeys) {
    return Object.keys(value).every((key) => allowedKeys.has(key));
}
function isRecord(value) {
    return typeof value === "object" && value !== null;
}
