import { CliError } from '../../../errors/index.js';
import { exportCanonicalAgentToCodexRole, } from './export-to-codex.js';
import { buildCodexMaterializedTargetRoleName, sanitizeCodexRoleName, } from './shared.js';
function requireNonEmpty(value, label) {
    const normalized = value.trim();
    if (!normalized) {
        throw new CliError(`Cannot materialize Codex role: missing ${label}.`);
    }
    return normalized;
}
export function buildCodexMaterializedRoleName({ agentName, model, effort, }) {
    const roleName = buildCodexMaterializedTargetRoleName({
        agentName,
        model,
        effort,
    });
    if (!roleName) {
        throw new CliError('Cannot materialize Codex role: missing role name.');
    }
    return roleName;
}
function codexExtensionObject(agent) {
    const extension = agent.extensions.x_codex;
    if (!extension || typeof extension !== 'object' || Array.isArray(extension)) {
        return {};
    }
    return { ...extension };
}
export function materializeCodexRole({ agent, model, effort, roleName, }) {
    const materializedModel = requireNonEmpty(model, 'model');
    const materializedEffort = requireNonEmpty(effort, 'effort');
    const materializedRoleName = roleName
        ? sanitizeCodexRoleName(roleName)
        : buildCodexMaterializedRoleName({
            agentName: agent.name,
            model: materializedModel,
            effort: materializedEffort,
        });
    if (!materializedRoleName) {
        throw new CliError('Cannot materialize Codex role: missing role name.');
    }
    return exportCanonicalAgentToCodexRole({
        ...agent,
        name: materializedRoleName,
        frontmatter: {
            ...agent.frontmatter,
            name: materializedRoleName,
        },
        extensions: {
            ...agent.extensions,
            x_codex: {
                ...codexExtensionObject(agent),
                model: materializedModel,
                model_reasoning_effort: materializedEffort,
            },
        },
    });
}
