import { CliError } from '../../../errors/index.js';
import TOML from '@iarna/toml';
import { stringifyToml } from './shared.js';
function parseConfig(content) {
    if (!content || content.trim() === '') {
        return {};
    }
    try {
        const parsed = TOML.parse(content);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            throw new CliError('Codex config TOML must parse to an object.');
        }
        return parsed;
    }
    catch (error) {
        if (error instanceof CliError) {
            throw error;
        }
        throw new CliError(`Failed to parse .codex/config.toml: ${error instanceof Error ? error.message : 'unknown parse error'}`);
    }
}
function getObject(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return {};
    }
    return { ...value };
}
function getFiniteNumber(value) {
    return typeof value === 'number' && Number.isFinite(value) ? value : null;
}
/** Reads a valid numeric agents.max_depth value from Codex TOML content. */
export function readCodexMaxDepth(content) {
    const parsed = parseConfig(content);
    const agents = getObject(parsed.agents);
    return getFiniteNumber(agents.max_depth);
}
/** Merges managed Codex roles and required shared agent configuration. */
export function mergeCodexConfig({ existingContent, desiredRoles, staleManagedRoles = [], inheritedMaxDepth, }) {
    const parsed = parseConfig(existingContent);
    const features = getObject(parsed.features);
    const agents = getObject(parsed.agents);
    const targetMaxDepth = getFiniteNumber(agents.max_depth);
    const validInheritedMaxDepth = getFiniteNumber(inheritedMaxDepth);
    agents.max_depth = Math.max(2, targetMaxDepth ?? 2, validInheritedMaxDepth ?? 2);
    const nextConfig = {
        ...parsed,
        features: {
            ...features,
            multi_agent: true,
        },
        agents,
    };
    for (const role of desiredRoles) {
        agents[role.roleName] = {
            ...getObject(agents[role.roleName]),
            description: role.description,
            config_file: role.configFile,
        };
    }
    const removedRoles = [];
    for (const staleRole of staleManagedRoles) {
        if (staleRole in agents) {
            delete agents[staleRole];
            removedRoles.push(staleRole);
        }
    }
    const mergedContent = stringifyToml(nextConfig);
    const changed = (existingContent ?? '').trimEnd() !== mergedContent.trimEnd();
    return {
        mergedContent,
        changed,
        removedRoles,
    };
}
/** Merges one managed Codex role using the shared configuration contract. */
export function mergeCodexConfigForRole({ existingContent, role, staleManagedRoles = [], inheritedMaxDepth, }) {
    return mergeCodexConfig({
        existingContent,
        desiredRoles: [role],
        staleManagedRoles,
        inheritedMaxDepth,
    });
}
