"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkerEventHookDraftParseError = exports.WorkerPullRequestReviewNecessityParseError = exports.WorkerWorkflowPlanReviewParseError = exports.WorkerWorkflowTemplateFitReviewParseError = exports.WorkerFollowupProposalReviewParseError = exports.WorkerAiWorkflowOptionAutofillParseError = exports.WorkerTemplateUpdateParseError = exports.WorkerTemplateDraftParseError = exports.WorkerIssueDraftParseError = exports.DECISION_START_MARKER = exports.DECISION_END_MARKER = void 0;
exports.parseWorkerDecision = parseWorkerDecision;
exports.parseWorkerContinuationIssueDecision = parseWorkerContinuationIssueDecision;
exports.parseWorkerIssueDraftDecision = parseWorkerIssueDraftDecision;
exports.parseWorkerTemplateDraftDecision = parseWorkerTemplateDraftDecision;
exports.parseWorkerTemplateUpdateDecision = parseWorkerTemplateUpdateDecision;
exports.parseWorkerAiWorkflowOptionAutofillDecision = parseWorkerAiWorkflowOptionAutofillDecision;
exports.parseWorkerFollowupProposalReviewDecision = parseWorkerFollowupProposalReviewDecision;
exports.parseWorkerWorkflowTemplateFitReviewDecision = parseWorkerWorkflowTemplateFitReviewDecision;
exports.parseWorkerWorkflowPlanReviewDecision = parseWorkerWorkflowPlanReviewDecision;
exports.parseWorkerPullRequestReviewNecessityDecision = parseWorkerPullRequestReviewNecessityDecision;
exports.parseWorkerEventHookResult = parseWorkerEventHookResult;
exports.parseWorkerEventHookDraftDecision = parseWorkerEventHookDraftDecision;
// biome-ignore lint/nursery/noExcessiveLinesPerFile: Worker decision parsing remains centralized across structured worker contracts.
const zod_1 = require("zod");
const catalog_1 = require("../i18n/catalog");
const decision_contract_1 = require("./decision-contract");
const errors_1 = require("./errors");
const issue_draft_contract_1 = require("./issue-draft-contract");
const event_hook_draft_contract_1 = require("./event-hook-draft-contract");
const template_draft_contract_1 = require("./template-draft-contract");
const template_update_contract_1 = require("./template-update-contract");
const ai_workflow_option_autofill_contract_1 = require("./ai-workflow-option-autofill-contract");
const followup_proposal_review_contract_1 = require("./followup-proposal-review-contract");
const workflow_template_fit_review_contract_1 = require("./workflow-template-fit-review-contract");
const workflow_plan_review_contract_1 = require("./workflow-plan-review-contract");
const pull_request_review_necessity_contract_1 = require("./pull-request-review-necessity-contract");
const event_hook_contract_1 = require("./event-hook-contract");
const structured_draft_metadata_1 = require("./structured-draft-metadata");
const decision_output_1 = require("./decision-output");
var decision_output_2 = require("./decision-output");
Object.defineProperty(exports, "DECISION_END_MARKER", { enumerable: true, get: function () { return decision_output_2.DECISION_END_MARKER; } });
Object.defineProperty(exports, "DECISION_START_MARKER", { enumerable: true, get: function () { return decision_output_2.DECISION_START_MARKER; } });
class WorkerRepairableStructuredDecisionParseError extends errors_1.WorkerDecisionParseError {
    constructor(diagnosticMessage, input) {
        super(diagnosticMessage, {
            ...(input.cause instanceof Error ? { cause: input.cause } : {}),
            locale: input.locale,
            publicMessage: input.repairKind === "missing"
                ? (0, catalog_1.translate)(input.locale, "worker.error.decisionBlockMissing")
                : (0, catalog_1.translate)(input.locale, "worker.error.decisionPayloadInvalid"),
            decisionBlock: input.decisionBlock,
            issues: [...input.issues],
            validationIssues: [...input.issues],
            repairEligible: true,
        });
    }
}
class WorkerIssueDraftParseError extends WorkerRepairableStructuredDecisionParseError {
    issueDraftRepairKind;
    constructor(diagnosticMessage, input) {
        const { issueDraftRepairKind, ...repairInput } = input;
        super(diagnosticMessage, {
            repairKind: issueDraftRepairKind,
            ...repairInput,
        });
        this.name = "WorkerIssueDraftParseError";
        this.issueDraftRepairKind = issueDraftRepairKind;
    }
}
exports.WorkerIssueDraftParseError = WorkerIssueDraftParseError;
class WorkerTemplateDraftParseError extends WorkerRepairableStructuredDecisionParseError {
    templateDraftRepairKind;
    constructor(diagnosticMessage, input) {
        const { templateDraftRepairKind, ...repairInput } = input;
        super(diagnosticMessage, {
            repairKind: templateDraftRepairKind,
            ...repairInput,
        });
        this.name = "WorkerTemplateDraftParseError";
        this.templateDraftRepairKind = templateDraftRepairKind;
    }
}
exports.WorkerTemplateDraftParseError = WorkerTemplateDraftParseError;
class WorkerTemplateUpdateParseError extends WorkerRepairableStructuredDecisionParseError {
    templateUpdateRepairKind;
    constructor(diagnosticMessage, input) {
        const { templateUpdateRepairKind, ...repairInput } = input;
        super(diagnosticMessage, {
            repairKind: templateUpdateRepairKind,
            ...repairInput,
        });
        this.name = "WorkerTemplateUpdateParseError";
        this.templateUpdateRepairKind = templateUpdateRepairKind;
    }
}
exports.WorkerTemplateUpdateParseError = WorkerTemplateUpdateParseError;
class WorkerAiWorkflowOptionAutofillParseError extends WorkerRepairableStructuredDecisionParseError {
    aiWorkflowOptionAutofillRepairKind;
    constructor(diagnosticMessage, input) {
        const { aiWorkflowOptionAutofillRepairKind, ...repairInput } = input;
        super(diagnosticMessage, {
            repairKind: aiWorkflowOptionAutofillRepairKind,
            ...repairInput,
        });
        this.name = "WorkerAiWorkflowOptionAutofillParseError";
        this.aiWorkflowOptionAutofillRepairKind =
            aiWorkflowOptionAutofillRepairKind;
    }
}
exports.WorkerAiWorkflowOptionAutofillParseError = WorkerAiWorkflowOptionAutofillParseError;
class WorkerFollowupProposalReviewParseError extends WorkerRepairableStructuredDecisionParseError {
    followupProposalReviewRepairKind;
    constructor(diagnosticMessage, input) {
        const { followupProposalReviewRepairKind, ...repairInput } = input;
        super(diagnosticMessage, {
            repairKind: followupProposalReviewRepairKind,
            ...repairInput,
        });
        this.name = "WorkerFollowupProposalReviewParseError";
        this.followupProposalReviewRepairKind = followupProposalReviewRepairKind;
    }
}
exports.WorkerFollowupProposalReviewParseError = WorkerFollowupProposalReviewParseError;
class WorkerWorkflowTemplateFitReviewParseError extends WorkerRepairableStructuredDecisionParseError {
    workflowTemplateFitReviewRepairKind;
    constructor(diagnosticMessage, input) {
        const { workflowTemplateFitReviewRepairKind, ...repairInput } = input;
        super(diagnosticMessage, {
            repairKind: workflowTemplateFitReviewRepairKind,
            ...repairInput,
        });
        this.name = "WorkerWorkflowTemplateFitReviewParseError";
        this.workflowTemplateFitReviewRepairKind =
            workflowTemplateFitReviewRepairKind;
    }
}
exports.WorkerWorkflowTemplateFitReviewParseError = WorkerWorkflowTemplateFitReviewParseError;
class WorkerWorkflowPlanReviewParseError extends WorkerRepairableStructuredDecisionParseError {
    workflowPlanReviewRepairKind;
    constructor(diagnosticMessage, input) {
        const { workflowPlanReviewRepairKind, ...repairInput } = input;
        super(diagnosticMessage, {
            repairKind: workflowPlanReviewRepairKind,
            ...repairInput,
        });
        this.name = "WorkerWorkflowPlanReviewParseError";
        this.workflowPlanReviewRepairKind = workflowPlanReviewRepairKind;
    }
}
exports.WorkerWorkflowPlanReviewParseError = WorkerWorkflowPlanReviewParseError;
class WorkerPullRequestReviewNecessityParseError extends WorkerRepairableStructuredDecisionParseError {
    pullRequestReviewNecessityRepairKind;
    constructor(diagnosticMessage, input) {
        const { pullRequestReviewNecessityRepairKind, ...repairInput } = input;
        super(diagnosticMessage, {
            repairKind: pullRequestReviewNecessityRepairKind,
            ...repairInput,
        });
        this.name = "WorkerPullRequestReviewNecessityParseError";
        this.pullRequestReviewNecessityRepairKind =
            pullRequestReviewNecessityRepairKind;
    }
}
exports.WorkerPullRequestReviewNecessityParseError = WorkerPullRequestReviewNecessityParseError;
class WorkerEventHookDraftParseError extends WorkerRepairableStructuredDecisionParseError {
    eventHookDraftRepairKind;
    constructor(diagnosticMessage, input) {
        const { eventHookDraftRepairKind, ...repairInput } = input;
        super(diagnosticMessage, {
            repairKind: eventHookDraftRepairKind,
            ...repairInput,
        });
        this.name = "WorkerEventHookDraftParseError";
        this.eventHookDraftRepairKind = eventHookDraftRepairKind;
    }
}
exports.WorkerEventHookDraftParseError = WorkerEventHookDraftParseError;
const issueDraftDecisionConfig = createStructuredDraftDecisionConfig({
    parseValue: (rawValue, input) => (0, issue_draft_contract_1.buildWorkerIssueDraftContract)(input).schema.parse(rawValue),
    validateSemanticRules: issue_draft_contract_1.validateWorkerIssueDraftSemanticRules,
    parseErrorConstructor: WorkerIssueDraftParseError,
    metadata: structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.issueDraft,
});
const templateDraftDecisionConfig = createStructuredDraftDecisionConfig({
    parseValue: (rawValue, input) => (0, template_draft_contract_1.buildWorkerTemplateDraftContract)(input).schema.parse(rawValue),
    validateSemanticRules: template_draft_contract_1.validateWorkerTemplateDraftSemanticRules,
    parseErrorConstructor: WorkerTemplateDraftParseError,
    metadata: structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.templateDraft,
});
const templateUpdateDecisionConfig = createStructuredDraftDecisionConfig({
    parseValue: (rawValue, input) => (0, template_update_contract_1.buildWorkerTemplateUpdateContract)(input).schema.parse(rawValue),
    validateSemanticRules: template_update_contract_1.validateWorkerTemplateUpdateSemanticRules,
    parseErrorConstructor: WorkerTemplateUpdateParseError,
    metadata: structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.templateUpdate,
});
const aiWorkflowOptionAutofillDecisionConfig = createStructuredDraftDecisionConfig({
    parseValue: (rawValue, input) => (0, ai_workflow_option_autofill_contract_1.buildWorkerAiWorkflowOptionAutofillContract)(input).schema.parse(rawValue),
    validateSemanticRules: ai_workflow_option_autofill_contract_1.validateWorkerAiWorkflowOptionAutofillSemanticRules,
    parseErrorConstructor: WorkerAiWorkflowOptionAutofillParseError,
    metadata: structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.aiWorkflowOptionAutofill,
});
const followupProposalReviewDecisionConfig = createStructuredDraftDecisionConfig({
    parseValue: (rawValue, input) => (0, followup_proposal_review_contract_1.buildWorkerFollowupProposalReviewContract)(input).schema.parse(rawValue),
    validateSemanticRules: followup_proposal_review_contract_1.validateWorkerFollowupProposalReviewSemanticRules,
    parseErrorConstructor: WorkerFollowupProposalReviewParseError,
    metadata: structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.followupProposalReview,
});
const workflowTemplateFitReviewDecisionConfig = createStructuredDraftDecisionConfig({
    parseValue: (rawValue, input) => (0, workflow_template_fit_review_contract_1.buildWorkerWorkflowTemplateFitReviewContract)(input).schema.parse(rawValue),
    validateSemanticRules: workflow_template_fit_review_contract_1.validateWorkerWorkflowTemplateFitReviewSemanticRules,
    parseErrorConstructor: WorkerWorkflowTemplateFitReviewParseError,
    metadata: structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.workflowTemplateFitReview,
});
const workflowPlanReviewDecisionConfig = createStructuredDraftDecisionConfig({
    parseValue: (rawValue, input) => (0, workflow_plan_review_contract_1.buildWorkerWorkflowPlanReviewContract)(input).schema.parse(rawValue),
    validateSemanticRules: workflow_plan_review_contract_1.validateWorkerWorkflowPlanReviewSemanticRules,
    parseErrorConstructor: WorkerWorkflowPlanReviewParseError,
    metadata: structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.workflowPlanReview,
});
const pullRequestReviewNecessityDecisionConfig = createStructuredDraftDecisionConfig({
    parseValue: (rawValue, input) => (0, pull_request_review_necessity_contract_1.buildWorkerPullRequestReviewNecessityContract)(input).schema.parse(rawValue),
    validateSemanticRules: pull_request_review_necessity_contract_1.validateWorkerPullRequestReviewNecessitySemanticRules,
    parseErrorConstructor: WorkerPullRequestReviewNecessityParseError,
    metadata: structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.pullRequestReviewNecessity,
});
const eventHookDraftDecisionConfig = createStructuredDraftDecisionConfig({
    parseValue: (rawValue, input) => (0, event_hook_draft_contract_1.buildWorkerEventHookDraftContract)(input).schema.parse(rawValue),
    validateSemanticRules: event_hook_draft_contract_1.validateWorkerEventHookDraftSemanticRules,
    parseErrorConstructor: WorkerEventHookDraftParseError,
    metadata: structured_draft_metadata_1.STRUCTURED_DRAFT_METADATA.eventHookDraft,
});
function parseWorkerDecision(rawOutput, options = catalog_1.DEFAULT_APP_LOCALE) {
    const { locale, workflow } = normalizeParseOptions(options);
    return parseDecisionOutput({
        rawOutput,
        parseJson: (rawJson) => parseDecisionJson(rawJson, locale, workflow),
        createMissingError: () => createDecisionBlockMissingError(locale),
    });
}
function parseWorkerContinuationIssueDecision(rawOutput, locale = catalog_1.DEFAULT_APP_LOCALE) {
    return parseDecisionOutput({
        rawOutput,
        parseJson: (rawJson) => parseContinuationIssueJson(rawJson, locale),
        createMissingError: () => createDecisionBlockMissingError(locale),
    });
}
function parseWorkerIssueDraftDecision(rawOutput, input) {
    return parseStructuredDraftDecision({
        rawOutput,
        decisionInput: input.draftInput,
        locale: input.locale,
        config: issueDraftDecisionConfig,
    });
}
function parseWorkerTemplateDraftDecision(rawOutput, input) {
    return parseStructuredDraftDecision({
        rawOutput,
        decisionInput: input.draftInput,
        locale: input.locale,
        config: templateDraftDecisionConfig,
    });
}
function parseWorkerTemplateUpdateDecision(rawOutput, input) {
    return parseStructuredDraftDecision({
        rawOutput,
        decisionInput: input.updateInput,
        locale: input.locale,
        config: templateUpdateDecisionConfig,
    });
}
function parseWorkerAiWorkflowOptionAutofillDecision(rawOutput, input) {
    return parseStructuredDraftDecision({
        rawOutput,
        decisionInput: input.autofillInput,
        locale: input.locale,
        config: aiWorkflowOptionAutofillDecisionConfig,
    });
}
function parseWorkerFollowupProposalReviewDecision(rawOutput, input) {
    return parseStructuredDraftDecision({
        rawOutput,
        decisionInput: input.reviewInput,
        locale: input.locale,
        config: followupProposalReviewDecisionConfig,
    });
}
function parseWorkerWorkflowTemplateFitReviewDecision(rawOutput, input) {
    return parseStructuredDraftDecision({
        rawOutput,
        decisionInput: input.reviewInput,
        locale: input.locale,
        config: workflowTemplateFitReviewDecisionConfig,
    });
}
function parseWorkerWorkflowPlanReviewDecision(rawOutput, input) {
    return parseStructuredDraftDecision({
        rawOutput,
        decisionInput: input.reviewInput,
        locale: input.locale,
        config: workflowPlanReviewDecisionConfig,
    });
}
function parseWorkerPullRequestReviewNecessityDecision(rawOutput, input) {
    return parseStructuredDraftDecision({
        rawOutput,
        decisionInput: input.decisionInput,
        locale: input.locale,
        config: pullRequestReviewNecessityDecisionConfig,
    });
}
function parseWorkerEventHookResult(rawOutput, locale = catalog_1.DEFAULT_APP_LOCALE) {
    return parseDecisionOutput({
        rawOutput,
        parseJson: (rawJson) => parseEventHookJson(rawJson, locale),
        createMissingError: () => createDecisionBlockMissingError(locale),
    });
}
function parseWorkerEventHookDraftDecision(rawOutput, input) {
    return parseStructuredDraftDecision({
        rawOutput,
        decisionInput: input.draftInput,
        locale: input.locale,
        config: eventHookDraftDecisionConfig,
    });
}
function createRepairableStructuredDecisionConfig(input) {
    return {
        parseValue: input.parseValue,
        validateSemanticRules: input.validateSemanticRules,
        isExpectedParseError: input.isExpectedParseError,
        createParseError: (diagnosticMessage, errorInput) => input.createError(diagnosticMessage, errorInput),
    };
}
function createStructuredDraftDecisionConfig(input) {
    return createRepairableStructuredDecisionConfig({
        parseValue: input.parseValue,
        validateSemanticRules: input.validateSemanticRules,
        isExpectedParseError: (error) => error instanceof input.parseErrorConstructor,
        createError: (diagnosticMessage, errorInput) => new input.parseErrorConstructor(diagnosticMessage, toStructuredDraftParseErrorConstructorInput(input.metadata, errorInput)),
    });
}
function parseStructuredDraftDecision(input) {
    const locale = input.locale ?? catalog_1.DEFAULT_APP_LOCALE;
    return parseDecisionOutput({
        rawOutput: input.rawOutput,
        parseJson: (rawJson) => parseRepairableStructuredDecisionJson({
            rawJson,
            decisionInput: input.decisionInput,
            locale,
            config: input.config,
        }),
        createMissingError: () => createRepairableBlockMissingError(locale, input.config.createParseError),
    });
}
function parseDecisionOutput(input) {
    const directJson = (0, decision_output_1.extractWorkerDecisionBlockFromText)(input.rawOutput);
    let directParseError = null;
    if (directJson !== null) {
        try {
            return input.parseJson(directJson);
        }
        catch (error) {
            if (error instanceof errors_1.WorkerDecisionParseError) {
                directParseError = error;
            }
            else {
                throw error;
            }
        }
    }
    const structuredJson = (0, decision_output_1.extractWorkerDecisionBlockFromStructuredOutput)(input.rawOutput);
    if (structuredJson !== null) {
        return input.parseJson(structuredJson);
    }
    if (directParseError !== null) {
        throw directParseError;
    }
    throw input.createMissingError();
}
function parseDecisionJson(rawJson, locale, workflow) {
    const rawValue = parseDecisionJsonValueOrThrow(rawJson, locale, createDecisionPayloadInvalidError);
    try {
        const parsed = (0, decision_contract_1.buildWorkerDecisionSchema)(workflow).parse(rawValue);
        const plan = parseDecisionPlan(parsed.plan);
        if (parsed.workflow === undefined || parsed.workflow === null) {
            return buildWorkerDecision(parsed, parsed.workflow === null ? null : undefined, parsed.selection, plan, parsed.planPatch);
        }
        return buildWorkerDecision(parsed, {
            mode: parsed.workflow.mode,
            templateName: parsed.workflow.templateName,
        }, parsed.selection, plan, parsed.planPatch);
    }
    catch (error) {
        if (error instanceof errors_1.WorkerDecisionParseError) {
            throw error;
        }
        if (error instanceof zod_1.z.ZodError) {
            throw createDecisionPayloadInvalidError(error, locale, rawJson, (0, decision_contract_1.toWorkerDecisionValidationIssues)(error));
        }
        throw createDecisionPayloadInvalidError(error, locale, rawJson, (0, decision_contract_1.toWorkerDecisionValidationIssues)(error));
    }
}
function parseContinuationIssueJson(rawJson, locale) {
    const rawValue = parseDecisionJsonValueOrThrow(rawJson, locale, createDecisionPayloadInvalidError);
    try {
        return (0, decision_contract_1.buildWorkerContinuationIssueContract)().schema.parse(rawValue);
    }
    catch (error) {
        if (error instanceof zod_1.z.ZodError) {
            throw createDecisionPayloadInvalidError(error, locale, rawJson, (0, decision_contract_1.toWorkerDecisionValidationIssues)(error));
        }
        throw createDecisionPayloadInvalidError(error, locale, rawJson, (0, decision_contract_1.toWorkerDecisionValidationIssues)(error));
    }
}
function parseEventHookJson(rawJson, locale) {
    const rawValue = parseDecisionJsonValueOrThrow(rawJson, locale, createNonRepairableDecisionPayloadInvalidError);
    try {
        return event_hook_contract_1.workerEventHookResultSchema.parse(rawValue);
    }
    catch (error) {
        if (error instanceof zod_1.z.ZodError) {
            throw createNonRepairableDecisionPayloadInvalidError(error, locale, rawJson, (0, decision_contract_1.toWorkerDecisionValidationIssues)(error));
        }
        throw createNonRepairableDecisionPayloadInvalidError(error, locale, rawJson, (0, decision_contract_1.toWorkerDecisionValidationIssues)(error));
    }
}
function parseRepairableStructuredDecisionJson(input) {
    const rawValue = parseDecisionJsonValueOrThrow(input.rawJson, input.locale, (error, locale, decisionBlock, validationIssues) => createRepairablePayloadInvalidError(error, locale, decisionBlock, validationIssues, input.config.createParseError));
    try {
        const parsed = input.config.parseValue(rawValue, input.decisionInput);
        const semanticIssues = input.config.validateSemanticRules(parsed, input.decisionInput);
        if (semanticIssues.length > 0) {
            throw createRepairableSemanticInvalidError(input.locale, input.rawJson, semanticIssues, input.config.createParseError);
        }
        return parsed;
    }
    catch (error) {
        if (input.config.isExpectedParseError(error)) {
            throw error;
        }
        throw createRepairablePayloadInvalidError(error, input.locale, input.rawJson, (0, decision_contract_1.toWorkerDecisionValidationIssues)(error), input.config.createParseError);
    }
}
function parseDecisionPlan(rawPlan) {
    if (rawPlan === undefined) {
        return undefined;
    }
    if (rawPlan === null) {
        return null;
    }
    return rawPlan;
}
function createDecisionBlockMissingError(locale) {
    return new errors_1.WorkerDecisionParseError((0, catalog_1.translate)(locale, "worker.error.decisionBlockMissing"), {
        locale,
        publicMessage: (0, catalog_1.translate)(locale, "worker.error.decisionBlockMissing"),
        decisionBlock: null,
        issues: [],
        repairEligible: false,
    });
}
function createDecisionPayloadInvalidError(error, locale, decisionBlock, validationIssues) {
    return createPayloadInvalidError({
        error,
        locale,
        decisionBlock,
        validationIssues,
        repairEligible: decisionBlock !== null,
    });
}
function createNonRepairableDecisionPayloadInvalidError(error, locale, decisionBlock, validationIssues) {
    return createPayloadInvalidError({
        error,
        locale,
        decisionBlock,
        validationIssues,
        repairEligible: false,
    });
}
function createPayloadInvalidError(input) {
    const issues = resolveValidationIssues(input.error, input.validationIssues);
    const diagnosticMessage = formatDecisionParseFailedDiagnostic(input.locale, issues);
    return new errors_1.WorkerDecisionParseError(diagnosticMessage, {
        ...(input.error instanceof Error ? { cause: input.error } : {}),
        locale: input.locale,
        publicMessage: (0, catalog_1.translate)(input.locale, "worker.error.decisionPayloadInvalid"),
        decisionBlock: input.decisionBlock,
        issues,
        validationIssues: issues,
        repairEligible: input.repairEligible,
    });
}
function createRepairableBlockMissingError(locale, createParseError) {
    const message = (0, catalog_1.translate)(locale, "worker.error.decisionBlockMissing");
    return createParseError(message, {
        repairKind: "missing",
        locale,
        decisionBlock: null,
        issues: [
            {
                path: [],
                code: "decision_block_missing",
                message,
            },
        ],
    });
}
function createRepairablePayloadInvalidError(error, locale, decisionBlock, validationIssues, createParseError) {
    const issues = resolveValidationIssues(error, validationIssues);
    return createParseError(formatDecisionParseFailedDiagnostic(locale, issues), {
        repairKind: "schema_invalid",
        locale,
        decisionBlock,
        issues,
        cause: error,
    });
}
function createRepairableSemanticInvalidError(locale, decisionBlock, validationIssues, createParseError) {
    return createParseError(formatDecisionParseFailedDiagnostic(locale, validationIssues), {
        repairKind: "semantic_invalid",
        locale,
        decisionBlock,
        issues: validationIssues,
    });
}
function toRepairableParseErrorConstructorInput(input) {
    return {
        locale: input.locale,
        decisionBlock: input.decisionBlock,
        issues: input.issues,
        ...(input.cause === undefined ? {} : { cause: input.cause }),
    };
}
function toStructuredDraftParseErrorConstructorInput(metadata, input) {
    return {
        [metadata.repairKindProperty]: input.repairKind,
        ...toRepairableParseErrorConstructorInput(input),
    };
}
function resolveValidationIssues(error, validationIssues) {
    return validationIssues.length > 0
        ? validationIssues
        : (0, decision_contract_1.toWorkerDecisionValidationIssues)(error);
}
function formatDecisionParseFailedDiagnostic(locale, issues) {
    return (0, catalog_1.translate)(locale, "worker.error.decisionParseFailed", {
        message: (0, decision_contract_1.formatWorkerDecisionValidationIssues)(issues),
    });
}
function normalizeParseOptions(options) {
    if (typeof options === "string") {
        return { locale: options, workflow: null };
    }
    return {
        locale: options.locale ?? catalog_1.DEFAULT_APP_LOCALE,
        workflow: options.workflow ?? null,
    };
}
function parseDecisionJsonValueOrThrow(rawJson, locale, createPayloadInvalidError) {
    try {
        return parseDecisionJsonValue(rawJson);
    }
    catch (error) {
        throw createPayloadInvalidError(error, locale, rawJson, (0, decision_contract_1.toWorkerDecisionValidationIssues)(error));
    }
}
function parseDecisionJsonValue(rawJson) {
    try {
        return JSON.parse(rawJson);
    }
    catch (error) {
        const repairedJson = escapeControlCharactersInJsonStrings(rawJson);
        if (repairedJson === rawJson) {
            throw error;
        }
        try {
            return JSON.parse(repairedJson);
        }
        catch {
            throw error;
        }
    }
}
function escapeControlCharactersInJsonStrings(rawJson) {
    const repaired = [];
    let inString = false;
    let escaping = false;
    for (const character of rawJson) {
        if (!inString) {
            repaired.push(character);
            if (character === '"') {
                inString = true;
            }
            continue;
        }
        if (escaping) {
            if (isValidJsonEscapeCharacter(character)) {
                repaired.push(character);
            }
            else {
                repaired.pop();
                repaired.push(character);
            }
            escaping = false;
            continue;
        }
        if (character === "\\") {
            repaired.push(character);
            escaping = true;
            continue;
        }
        if (character === '"') {
            repaired.push(character);
            inString = false;
            continue;
        }
        const escapedControlCharacter = escapeControlCharacterForJsonString(character);
        if (escapedControlCharacter !== null) {
            repaired.push(escapedControlCharacter);
            continue;
        }
        repaired.push(character);
    }
    return repaired.join("");
}
function isValidJsonEscapeCharacter(character) {
    return (character === '"' ||
        character === "\\" ||
        character === "/" ||
        character === "b" ||
        character === "f" ||
        character === "n" ||
        character === "r" ||
        character === "t" ||
        character === "u");
}
function escapeControlCharacterForJsonString(character) {
    switch (character) {
        case "\b":
            return "\\b";
        case "\f":
            return "\\f";
        case "\n":
            return "\\n";
        case "\r":
            return "\\r";
        case "\t":
            return "\\t";
        default: {
            const codePoint = character.charCodeAt(0);
            if (codePoint < 0x20) {
                return `\\u${codePoint.toString(16).padStart(4, "0")}`;
            }
            return null;
        }
    }
}
function buildWorkerDecision(parsed, workflow, selection, plan, planPatch) {
    const decision = {
        outcome: parsed.outcome,
        result: parsed.result,
    };
    if (parsed.commitMessage !== undefined) {
        decision.commitMessage = parsed.commitMessage;
    }
    if (parsed.priorityRank !== undefined) {
        decision.priorityRank = parsed.priorityRank;
    }
    if (parsed.issueTitle !== undefined) {
        decision.issueTitle = parsed.issueTitle.trim();
    }
    if (selection !== undefined) {
        decision.selection = selection;
    }
    if (parsed.contract !== undefined) {
        decision.contract = parsed.contract;
    }
    if (parsed.plan !== undefined) {
        decision.plan = plan ?? null;
    }
    if (parsed.planPatch !== undefined) {
        decision.planPatch = planPatch ?? null;
    }
    if (parsed.executionGuidance !== undefined) {
        decision.executionGuidance = parsed.executionGuidance;
    }
    if (parsed.predictedTouchedPaths !== undefined) {
        decision.predictedTouchedPaths = parsed.predictedTouchedPaths;
    }
    if (parsed.workflowStartApproval !== undefined) {
        decision.workflowStartApproval = parsed.workflowStartApproval;
    }
    if (parsed.continuation !== undefined) {
        decision.continuation = parsed.continuation;
    }
    if (parsed.followupRecommendation !== undefined) {
        decision.followupRecommendation = parsed.followupRecommendation;
    }
    if (parsed.needsHumanReason !== undefined) {
        decision.needsHumanReason = parsed.needsHumanReason;
    }
    if (parsed.stepResults !== undefined) {
        decision.stepResults = parsed.stepResults;
    }
    if (workflow !== undefined) {
        decision.workflow = workflow;
    }
    return decision;
}
