const maskSecret = (secret) => {
    if (!secret)
        return 'Not configured';
    const safeString = String(secret);
    if (safeString.length <= 4)
        return '••••';
    return `••••${safeString.slice(-4)}`;
};
const isGpt5ModelId = (modelId) => {
    if (!modelId)
        return false;
    return modelId.trim().toLowerCase().startsWith('gpt-5');
};
export const openaiModelTemplate = {
    provider: 'openai',
    label: 'New OpenAI Model',
    model: 'gpt-4.1',
    description: 'A new OpenAI model configuration',
    connection: {
        apiKey: ''
    },
    settings: {
        temperature: 0.7,
        maxTokens: 1000,
        topP: 1
    }
};
export const openaiModelDefinition = {
    id: 'openai',
    displayName: 'OpenAI',
    badgeClassName: 'bg-blue-100 text-blue-800',
    defaultModelTemplate: openaiModelTemplate,
    viewFields: [
        {
            label: 'Model',
            render: (model) => model.model || 'Not set'
        },
        {
            label: 'API Key',
            render: (model) => maskSecret(model.connection?.apiKey)
        },
        {
            label: 'Base URL',
            render: (model) => model.baseUrl || model.connection?.baseUrl || 'Default (api.openai.com)'
        },
        {
            label: 'Temperature',
            render: (model) => {
                if (isGpt5ModelId(model.model)) {
                    return 'Not applicable for GPT-5';
                }
                const value = model.settings?.temperature;
                return value ?? 'Default (0.7)';
            }
        },
        {
            label: 'Max Tokens',
            render: (model) => model.settings?.maxTokens ?? 1000
        },
        {
            label: 'Top P',
            render: (model) => {
                if (isGpt5ModelId(model.model)) {
                    return 'Not applicable for GPT-5';
                }
                const value = model.settings?.topP;
                return value ?? 'Default (1)';
            }
        },
        {
            label: 'Reasoning Effort',
            render: (model) => {
                if (!isGpt5ModelId(model.model)) {
                    return 'Only used by GPT-5';
                }
                const settings = (model.settings ?? {});
                const reasoningObject = settings.reasoning;
                const effort = typeof settings.reasoningEffort === 'string'
                    ? settings.reasoningEffort
                    : (typeof reasoningObject?.effort === 'string' ? reasoningObject.effort : undefined);
                return effort ?? 'Default (medium)';
            }
        },
        {
            label: 'Text Verbosity',
            render: (model) => {
                if (!isGpt5ModelId(model.model)) {
                    return 'Only used by GPT-5';
                }
                const settings = (model.settings ?? {});
                const textObject = settings.text;
                const verbosity = typeof settings.textVerbosity === 'string'
                    ? settings.textVerbosity
                    : (typeof textObject?.verbosity === 'string' ? textObject.verbosity : undefined);
                return verbosity ?? 'Default (medium)';
            }
        },
        {
            label: 'Legacy Messaging',
            render: (model) => (model.useLegacyMessages ? 'Enabled' : 'Disabled')
        }
    ],
    form: {
        schema: [
            ['label', {
                    type: 'string',
                    label: 'Model Name',
                    required: true,
                    description: 'Display name for this model configuration'
                }],
            ['model', {
                    type: 'string',
                    label: 'OpenAI Model',
                    enum: ['gpt-4.1', 'gpt-4o', 'gpt-5'],
                    required: true,
                    description: 'The OpenAI model identifier to use'
                }],
            ['description', {
                    type: 'string',
                    label: 'Description',
                    description: 'Optional description for this model configuration'
                }],
            ['temperature', {
                    type: 'number',
                    label: 'Temperature',
                    minimum: 0,
                    maximum: 2,
                    description: 'Sampling temperature (0-2)'
                }],
            ['maxTokens', {
                    type: 'integer',
                    label: 'Max Tokens',
                    minimum: 1,
                    maximum: 4096,
                    description: 'Maximum number of tokens to generate'
                }],
            ['topP', {
                    type: 'number',
                    label: 'Top P',
                    minimum: 0,
                    maximum: 1,
                    description: 'Nucleus sampling parameter'
                }],
            ['reasoningEffort', {
                    type: 'string',
                    label: 'Reasoning Effort',
                    enum: ['low', 'medium', 'high'],
                    default: 'medium',
                    description: 'For GPT-5 models, controls the amount of reasoning performed.'
                }],
            ['textVerbosity', {
                    type: 'string',
                    label: 'Text Verbosity',
                    enum: ['low', 'medium', 'high'],
                    default: 'medium',
                    description: 'For GPT-5 models, controls how expansive responses should be.'
                }],
            ['apiKey', {
                    type: 'string',
                    label: 'API Key',
                    required: true,
                    description: 'Your OpenAI API key'
                }],
            ['clientHeaders', {
                    type: 'object',
                    label: 'Client Headers',
                    description: 'Additional headers to include in requests to OpenAI (optional)'
                }],
            ['baseUrl', {
                    type: 'string',
                    label: 'Base URL',
                    description: 'Custom API base URL (optional)'
                }],
            ['logLevel', {
                    type: 'string',
                    label: 'Log Level',
                    enum: ['off', 'error', 'warn', 'info', 'debug'],
                    default: 'off',
                    description: 'Set the logging verbosity for the OpenAI client'
                }],
            ['apiMode', {
                    type: 'string',
                    label: 'API Mode',
                    enum: ['responses', 'chat_completions'],
                    default: 'responses',
                    description: 'Select the API mode to use'
                }],
            ['useLegacyMessages', {
                    type: 'boolean',
                    label: 'Use legacy message payload',
                    description: 'Format agent messages as { role, content } for legacy APIs',
                    default: false
                }]
        ],
        getInitialValues: (model) => {
            const settings = (model.settings ?? {});
            const reasoningObject = settings.reasoning;
            const textObject = settings.text;
            const reasoningEffort = typeof settings.reasoningEffort === 'string'
                ? settings.reasoningEffort
                : (typeof reasoningObject?.effort === 'string' ? reasoningObject.effort : undefined);
            const textVerbosity = typeof settings.textVerbosity === 'string'
                ? settings.textVerbosity
                : (typeof textObject?.verbosity === 'string' ? textObject.verbosity : undefined);
            return {
                label: model.label,
                model: model.model,
                description: model.description || '',
                apiKey: model.connection?.apiKey || '',
                baseUrl: model.baseUrl || model.connection?.baseUrl || '',
                temperature: settings.temperature ?? 0.7,
                maxTokens: settings.maxTokens ?? 1000,
                topP: settings.topP ?? 1,
                reasoningEffort: reasoningEffort ?? 'medium',
                textVerbosity: textVerbosity ?? 'medium',
                logLevel: model.logLevel ?? 'off',
                apiMode: model.apiMode ?? 'responses',
                clientHeaders: model.clientHeaders ?? {},
                useLegacyMessages: Boolean(model.useLegacyMessages)
            };
        },
        transformSubmit: (values, existingModel) => {
            const connection = {
                apiKey: values.apiKey || ''
            };
            const coerceClientHeaders = (input) => {
                if (!input || typeof input !== 'object' || Array.isArray(input)) {
                    return undefined;
                }
                const result = {};
                for (const [rawKey, rawValue] of Object.entries(input)) {
                    const key = rawKey.trim();
                    if (!key)
                        continue;
                    if (rawValue === null || rawValue === undefined)
                        continue;
                    let normalized;
                    if (typeof rawValue === 'string') {
                        normalized = rawValue;
                    }
                    else if (typeof rawValue === 'number' || typeof rawValue === 'boolean') {
                        normalized = String(rawValue);
                    }
                    else {
                        try {
                            normalized = JSON.stringify(rawValue);
                        }
                        catch {
                            normalized = String(rawValue);
                        }
                    }
                    result[key] = normalized;
                }
                return Object.keys(result).length > 0 ? result : undefined;
            };
            const resolvedClientHeaders = coerceClientHeaders(values.clientHeaders);
            const LOG_LEVEL_OPTIONS = ['off', 'error', 'warn', 'info', 'debug'];
            const isLogLevelOption = (value) => typeof value === 'string' && LOG_LEVEL_OPTIONS.includes(value);
            const resolvedLogLevel = isLogLevelOption(values.logLevel) ? values.logLevel : 'off';
            const API_MODE_OPTIONS = ['responses', 'chat_completions'];
            const isApiModeOption = (value) => typeof value === 'string' && API_MODE_OPTIONS.includes(value);
            const resolvedApiMode = isApiModeOption(values.apiMode) ? values.apiMode : 'responses';
            const useLegacyMessages = Boolean(values.useLegacyMessages);
            const baseUrl = values.baseUrl;
            const trimmedBaseUrl = typeof baseUrl === 'string' && baseUrl.trim() ? baseUrl.trim() : undefined;
            if (trimmedBaseUrl) {
                connection.baseUrl = trimmedBaseUrl;
            }
            const nextModelId = typeof values.model === 'string' && values.model.trim().length > 0
                ? values.model.trim()
                : existingModel.model;
            const gpt5Selected = isGpt5ModelId(nextModelId);
            const coerceNumber = (input, fallback, options) => {
                const numeric = typeof input === 'string' && input.trim().length === 0
                    ? Number.NaN
                    : Number(input);
                const base = Number.isFinite(numeric) ? numeric : fallback;
                const min = options?.min ?? Number.NEGATIVE_INFINITY;
                const max = options?.max ?? Number.POSITIVE_INFINITY;
                const clamped = Math.min(max, Math.max(min, base));
                if (options?.precision !== undefined) {
                    const factor = 10 ** options.precision;
                    return Math.round(clamped * factor) / factor;
                }
                return clamped;
            };
            const maxTokens = coerceNumber(values.maxTokens, 1000, { min: 1, precision: 0 });
            const settings = {
                maxTokens
            };
            if (gpt5Selected) {
                const reasoningEffort = typeof values.reasoningEffort === 'string' && values.reasoningEffort.trim().length > 0
                    ? values.reasoningEffort.trim()
                    : undefined;
                const textVerbosity = typeof values.textVerbosity === 'string' && values.textVerbosity.trim().length > 0
                    ? values.textVerbosity.trim()
                    : undefined;
                if (reasoningEffort) {
                    settings.reasoning = { effort: reasoningEffort };
                }
                if (textVerbosity) {
                    settings.text = { verbosity: textVerbosity };
                }
            }
            else {
                const temperature = coerceNumber(values.temperature, 0.7, { min: 0, max: 2, precision: 2 });
                const topP = coerceNumber(values.topP, 1, { min: 0, max: 1, precision: 2 });
                settings.temperature = temperature;
                settings.topP = topP;
            }
            return {
                provider: existingModel.provider,
                label: values.label,
                model: nextModelId,
                description: values.description || undefined,
                baseUrl: trimmedBaseUrl,
                connection,
                settings,
                ...(resolvedClientHeaders ? { clientHeaders: resolvedClientHeaders } : {}),
                logLevel: resolvedLogLevel,
                apiMode: resolvedApiMode,
                useLegacyMessages
            };
        },
        submitButtonText: 'Update Model'
    }
};
