"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseOverrideOption = parseOverrideOption;
exports.normalizeOverridePatchEntries = normalizeOverridePatchEntries;
const control_plane_config_1 = require("../config/control-plane-config");
const types_1 = require("./types");
const workflow_option_parse_shared_1 = require("./workflow-option-parse-shared");
function parseOverrideOption(tokens, index, option, seenOverrideFlags, arrayOverrideValues, inlineTrailingText) {
    if (option.repeatable !== true && seenOverrideFlags.has(option.flag)) {
        return (0, workflow_option_parse_shared_1.buildInvalidWorkflowCommandOptionResult)("duplicate-option", inlineTrailingText);
    }
    if (option.kind === "integer" || option.kind === "number") {
        const optionValue = (0, workflow_option_parse_shared_1.resolveCommandOptionValue)(tokens, index, inlineTrailingText, { allowValueStartingWithDash: workflow_option_parse_shared_1.isNegativeNumberToken });
        if (optionValue.kind === "invalid") {
            return optionValue;
        }
        seenOverrideFlags.add(option.flag);
        return parseNumberOverrideOption(tokens, index, option, optionValue.value);
    }
    const optionValue = (0, workflow_option_parse_shared_1.resolveCommandOptionValue)(tokens, index, inlineTrailingText);
    if (optionValue.kind === "invalid") {
        return optionValue;
    }
    seenOverrideFlags.add(option.flag);
    if (option.kind === "enum") {
        return parseEnumOverrideOption(tokens, index, option, optionValue.value);
    }
    if (option.kind === "boolean") {
        return parseBooleanOverrideOption(tokens, index, option, optionValue.value);
    }
    if (option.kind === "string") {
        return parseStringOverrideOption(tokens, index, option, optionValue.value);
    }
    if (option.kind === "worker") {
        return parseWorkerOverrideOption(tokens, index, option, optionValue.value);
    }
    if (option.kind === "workflow-template-list") {
        return parseWorkflowTemplateListOverrideOption(tokens, index, option, optionValue.value, arrayOverrideValues);
    }
    return parseStringArrayOverrideOption(tokens, index, option, optionValue.value, arrayOverrideValues);
}
function parseWorkflowTemplateListOverrideOption(tokens, index, option, value, arrayOverrideValues) {
    const values = parseStringArrayOptionValue(value);
    const normalizedValues = values.flatMap((entry) => {
        if (entry === "default") {
            return [entry];
        }
        const normalized = (0, types_1.normalizeFollowupWorkflowTemplateCandidate)(entry);
        return normalized === null ? [] : [normalized];
    });
    if (values.length === 0 ||
        normalizedValues.length !== values.length ||
        (normalizedValues.includes("default") &&
            (normalizedValues.length > 1 ||
                (arrayOverrideValues.get(option.path)?.length ?? 0) > 0))) {
        return (0, workflow_option_parse_shared_1.buildInvalidWorkflowCommandOptionValueResult)(tokens, index);
    }
    if (normalizedValues.length === 1 && normalizedValues[0] === "default") {
        arrayOverrideValues.set(option.path, ["default"]);
        return {
            kind: "entry",
            consumedTokens: 2,
        };
    }
    const existingValues = arrayOverrideValues.get(option.path);
    if (existingValues?.includes("default")) {
        return (0, workflow_option_parse_shared_1.buildInvalidWorkflowCommandOptionValueResult)(tokens, index);
    }
    arrayOverrideValues.set(option.path, [
        ...(existingValues ?? []),
        ...normalizedValues,
    ]);
    return {
        kind: "entry",
        consumedTokens: 2,
    };
}
function normalizeOverridePatchEntries(overrideEntries, arrayOverrideValues) {
    const entriesByPath = new Map();
    for (const entry of overrideEntries) {
        entriesByPath.set(entry.path, entry);
    }
    for (const [path, values] of arrayOverrideValues.entries()) {
        entriesByPath.set(path, {
            path,
            op: values.length === 1 && values[0] === "default" ? "inherit" : "set",
            ...(values.length === 1 && values[0] === "default"
                ? {}
                : { value: [...new Set(values)] }),
        });
    }
    const entries = [...entriesByPath.values()];
    if (entries.length === 0) {
        return { kind: "patch" };
    }
    return {
        kind: "patch",
        patch: { entries },
    };
}
function parseNumberOverrideOption(tokens, index, option, value) {
    if (value === "default") {
        return buildInheritOverrideOptionResult(option.path);
    }
    if (value === "off" && option.allowDisable === true) {
        return buildOperationOverrideOptionResult(option.path, "disable", 2);
    }
    const parsed = Number(value);
    if (!Number.isFinite(parsed) ||
        parsed < (option.min ?? Number.NEGATIVE_INFINITY) ||
        parsed > (option.max ?? Number.POSITIVE_INFINITY) ||
        value.trim().length === 0 ||
        (option.kind === "integer" && !Number.isInteger(parsed)) ||
        parsed < 0) {
        return (0, workflow_option_parse_shared_1.buildInvalidWorkflowCommandOptionValueResult)(tokens, index);
    }
    return {
        kind: "entry",
        entry: {
            path: option.path,
            op: "set",
            value: parsed,
        },
        consumedTokens: 2,
    };
}
function parseEnumOverrideOption(tokens, index, option, value) {
    const parsedValue = option.parseCliValue === undefined ? value : option.parseCliValue(value);
    if (parsedValue === null) {
        return (0, workflow_option_parse_shared_1.buildInvalidWorkflowCommandOptionValueResult)(tokens, index);
    }
    if (parsedValue === "default") {
        return buildInheritOverrideOptionResult(option.path);
    }
    if (!option.enumValues?.includes(parsedValue)) {
        return (0, workflow_option_parse_shared_1.buildInvalidWorkflowCommandOptionValueResult)(tokens, index);
    }
    return {
        kind: "entry",
        entry: {
            path: option.path,
            op: "set",
            value: parsedValue,
        },
        consumedTokens: 2,
    };
}
function parseBooleanOverrideOption(tokens, index, option, value) {
    if (value === "default") {
        return buildInheritOverrideOptionResult(option.path);
    }
    if (value !== "true" && value !== "false") {
        return (0, workflow_option_parse_shared_1.buildInvalidWorkflowCommandOptionValueResult)(tokens, index);
    }
    return {
        kind: "entry",
        entry: {
            path: option.path,
            op: "set",
            value: value === "true",
        },
        consumedTokens: 2,
    };
}
function parseStringOverrideOption(tokens, index, option, value) {
    if (value === "default") {
        return buildInheritOverrideOptionResult(option.path);
    }
    if (value.trim().length === 0) {
        return (0, workflow_option_parse_shared_1.buildInvalidWorkflowCommandOptionValueResult)(tokens, index);
    }
    return {
        kind: "entry",
        entry: {
            path: option.path,
            op: "set",
            value,
        },
        consumedTokens: 2,
    };
}
function parseWorkerOverrideOption(tokens, index, option, value) {
    if (value === "default") {
        return buildInheritOverrideOptionResult(option.path);
    }
    if (!isValidWorkflowWorkerOverrideValue(value)) {
        return (0, workflow_option_parse_shared_1.buildInvalidWorkflowCommandOptionValueResult)(tokens, index);
    }
    return {
        kind: "entry",
        entry: {
            path: option.path,
            op: "set",
            value: [value],
        },
        consumedTokens: 2,
    };
}
function isValidWorkflowWorkerOverrideValue(value) {
    return ((0, control_plane_config_1.isBuiltInWorkerName)(value) || control_plane_config_1.customWorkerIdSchema.safeParse(value).success);
}
function parseStringArrayOverrideOption(tokens, index, option, value, arrayOverrideValues) {
    const values = parseStringArrayOptionValue(value);
    if (values.length === 0) {
        return (0, workflow_option_parse_shared_1.buildInvalidWorkflowCommandOptionValueResult)(tokens, index);
    }
    if (values.length === 1 && values[0] === "default") {
        const existingValues = arrayOverrideValues.get(option.path);
        if (existingValues !== undefined && existingValues.length > 0) {
            return (0, workflow_option_parse_shared_1.buildInvalidWorkflowCommandOptionValueResult)(tokens, index);
        }
        arrayOverrideValues.set(option.path, ["default"]);
        return {
            kind: "entry",
            consumedTokens: 2,
        };
    }
    const existingValues = arrayOverrideValues.get(option.path);
    if (existingValues?.includes("default")) {
        return (0, workflow_option_parse_shared_1.buildInvalidWorkflowCommandOptionValueResult)(tokens, index);
    }
    arrayOverrideValues.set(option.path, [...(existingValues ?? []), ...values]);
    return {
        kind: "entry",
        consumedTokens: 2,
    };
}
function buildInheritOverrideOptionResult(path, consumedTokens = 2) {
    return {
        kind: "entry",
        entry: {
            path,
            op: "inherit",
        },
        consumedTokens,
    };
}
function buildOperationOverrideOptionResult(path, op, consumedTokens) {
    return {
        kind: "entry",
        entry: {
            path,
            op,
        },
        consumedTokens,
    };
}
function parseStringArrayOptionValue(rawValue) {
    return rawValue
        .split(",")
        .map((value) => value.trim())
        .filter((value) => value.length > 0);
}
