"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.exitOnApiCommandErrors = exports.applyClaudeExtendedContextPreference = exports.hasExplicitClaudeExtendedContext = exports.hasClaudeModelMapping = exports.parseApiCommandArgs = exports.collectUnexpectedApiArgs = exports.parseOptionalTargetFlag = exports.extractPositionalArgs = exports.sanitizeHelpText = exports.API_KNOWN_FLAGS = exports.API_VALUE_FLAGS = exports.API_BOOLEAN_FLAGS = void 0;
const target_metadata_1 = require("../../targets/target-metadata");
const extended_context_utils_1 = require("../../shared/extended-context-utils");
const ui_1 = require("../../utils/ui");
const arg_extractor_1 = require("../arg-extractor");
const MODEL_MAPPING_KEYS = ['default', 'opus', 'sonnet', 'haiku'];
exports.API_BOOLEAN_FLAGS = ['--force', '--yes', '-y', '--1m', '--no-1m'];
exports.API_VALUE_FLAGS = [
    '--base-url',
    '--api-key',
    '--model',
    '--extra-models',
    '--preset',
    '--cliproxy-provider',
    '--target',
];
exports.API_KNOWN_FLAGS = [...exports.API_BOOLEAN_FLAGS, ...exports.API_VALUE_FLAGS];
const API_VALUE_FLAG_SET = new Set(exports.API_VALUE_FLAGS);
function sanitizeHelpText(value) {
    return value
        .replace(/[\r\n\t]+/g, ' ')
        .replace(/[\x00-\x1f\x7f]/g, ' ')
        .replace(/\s+/g, ' ')
        .trim();
}
exports.sanitizeHelpText = sanitizeHelpText;
function applyRepeatedOption(args, flags, onValue, onMissing, allowDashValue = false) {
    let remaining = [...args];
    while (true) {
        const extracted = (0, arg_extractor_1.extractOption)(remaining, flags, {
            allowDashValue,
            knownFlags: exports.API_KNOWN_FLAGS,
        });
        if (!extracted.found) {
            return remaining;
        }
        if (extracted.missingValue || !extracted.value) {
            onMissing();
        }
        else {
            onValue(extracted.value);
        }
        remaining = extracted.remainingArgs;
    }
}
function extractPositionalArgs(args) {
    const positionals = [];
    for (let i = 0; i < args.length; i++) {
        const token = args[i];
        if (token === '--') {
            positionals.push(...args.slice(i + 1));
            break;
        }
        if (token.startsWith('-')) {
            if (!token.includes('=') && API_VALUE_FLAG_SET.has(token)) {
                const next = args[i + 1];
                if (next && !next.startsWith('-')) {
                    i++;
                }
            }
            continue;
        }
        positionals.push(token);
    }
    return positionals;
}
exports.extractPositionalArgs = extractPositionalArgs;
function parseTargetValue(value) {
    const normalized = value.trim().toLowerCase();
    if ((0, target_metadata_1.isPersistedTargetType)(normalized)) {
        return normalized;
    }
    return null;
}
function parseOptionalTargetFlag(args, knownFlags) {
    const extracted = (0, arg_extractor_1.extractOption)(args, ['--target'], {
        knownFlags,
    });
    if (!extracted.found) {
        return { remainingArgs: args, errors: [] };
    }
    if (extracted.missingValue || !extracted.value) {
        return { remainingArgs: extracted.remainingArgs, errors: ['Missing value for --target'] };
    }
    const target = parseTargetValue(extracted.value);
    if (!target) {
        return {
            remainingArgs: extracted.remainingArgs,
            errors: [`Invalid --target value "${extracted.value}". Use: ${(0, target_metadata_1.getPersistedTargetChoices)()}`],
        };
    }
    return { target, remainingArgs: extracted.remainingArgs, errors: [] };
}
exports.parseOptionalTargetFlag = parseOptionalTargetFlag;
function collectUnexpectedApiArgs(args, options) {
    const scanned = (0, arg_extractor_1.scanCommandArgs)(args, {
        knownFlags: options.knownFlags ?? [],
    });
    const errors = scanned.unknownFlags.map((flag) => `Unknown option: ${flag}`);
    if (scanned.positionals.length > options.maxPositionals) {
        errors.push(`Unexpected arguments: ${scanned.positionals.slice(options.maxPositionals).join(' ')}`);
    }
    return {
        positionals: scanned.positionals,
        errors,
    };
}
exports.collectUnexpectedApiArgs = collectUnexpectedApiArgs;
function parseApiCommandArgs(args, options = {}) {
    const enableExtendedContext = (0, arg_extractor_1.hasAnyFlag)(args, ['--1m']);
    const disableExtendedContext = (0, arg_extractor_1.hasAnyFlag)(args, ['--no-1m']);
    const result = {
        positionals: [],
        force: (0, arg_extractor_1.hasAnyFlag)(args, ['--force']),
        yes: (0, arg_extractor_1.hasAnyFlag)(args, ['--yes', '-y']),
        errors: [],
    };
    if (enableExtendedContext && disableExtendedContext) {
        result.errors.push('Cannot combine --1m and --no-1m');
    }
    else if (enableExtendedContext) {
        result.extendedContext = true;
    }
    else if (disableExtendedContext) {
        result.extendedContext = false;
    }
    let remaining = [...args];
    remaining = applyRepeatedOption(remaining, ['--base-url'], (value) => {
        result.baseUrl = value;
    }, () => {
        result.errors.push('Missing value for --base-url');
    }, false);
    remaining = applyRepeatedOption(remaining, ['--api-key'], (value) => {
        result.apiKey = value;
    }, () => {
        result.errors.push('Missing value for --api-key');
    }, false);
    remaining = applyRepeatedOption(remaining, ['--model'], (value) => {
        result.model = value;
    }, () => {
        result.errors.push('Missing value for --model');
    }, true);
    remaining = applyRepeatedOption(remaining, ['--extra-models'], (value) => {
        result.extraModels = value
            .split(',')
            .map((m) => m.trim())
            .filter((m) => m.length > 0);
    }, () => {
        result.errors.push('Missing value for --extra-models');
    }, false);
    remaining = applyRepeatedOption(remaining, ['--preset'], (value) => {
        result.preset = value;
    }, () => {
        result.errors.push('Missing value for --preset');
    }, false);
    remaining = applyRepeatedOption(remaining, ['--cliproxy-provider'], (value) => {
        result.cliproxyProvider = value.trim().toLowerCase();
    }, () => {
        result.errors.push('Missing value for --cliproxy-provider');
    }, false);
    remaining = applyRepeatedOption(remaining, ['--target'], (value) => {
        const target = parseTargetValue(value);
        if (!target) {
            result.errors.push(`Invalid --target value "${value}". Use: ${(0, target_metadata_1.getPersistedTargetChoices)()}`);
            return;
        }
        result.target = target;
    }, () => {
        result.errors.push('Missing value for --target');
    }, false);
    const unexpected = collectUnexpectedApiArgs(remaining, {
        knownFlags: exports.API_BOOLEAN_FLAGS,
        maxPositionals: options.maxPositionals ?? 1,
    });
    result.positionals = unexpected.positionals;
    result.name = unexpected.positionals[0];
    result.errors.push(...unexpected.errors);
    return result;
}
exports.parseApiCommandArgs = parseApiCommandArgs;
function hasClaudeModelMapping(models) {
    return MODEL_MAPPING_KEYS.some((key) => (0, extended_context_utils_1.isClaudeModelId)(models[key]));
}
exports.hasClaudeModelMapping = hasClaudeModelMapping;
function hasExplicitClaudeExtendedContext(models) {
    return MODEL_MAPPING_KEYS.some((key) => (0, extended_context_utils_1.isClaudeModelId)(models[key]) && (0, extended_context_utils_1.hasExtendedContextSuffix)(models[key]));
}
exports.hasExplicitClaudeExtendedContext = hasExplicitClaudeExtendedContext;
function applyClaudeExtendedContextPreference(models, enabled) {
    const nextModels = { ...models };
    for (const key of MODEL_MAPPING_KEYS) {
        const value = nextModels[key];
        if (!(0, extended_context_utils_1.isClaudeModelId)(value)) {
            continue;
        }
        nextModels[key] =
            enabled && (0, extended_context_utils_1.likelySupportsClaudeExtendedContext)(value)
                ? (0, extended_context_utils_1.applyExtendedContextSuffix)(value)
                : (0, extended_context_utils_1.stripExtendedContextSuffix)(value);
    }
    return nextModels;
}
exports.applyClaudeExtendedContextPreference = applyClaudeExtendedContextPreference;
function exitOnApiCommandErrors(errors) {
    if (errors.length === 0) {
        return;
    }
    errors.forEach((errorMessage) => {
        console.log((0, ui_1.fail)(errorMessage));
    });
    process.exit(1);
}
exports.exitOnApiCommandErrors = exitOnApiCommandErrors;
//# sourceMappingURL=shared.js.map