import { t, ti } from '../i18n/index.js';
import { getStatus, getWarning, setConfig, getSessionOps, generateCheckpoint, formatCheckpoint, analyzeSession, suggestExplorePrompt, } from '../engine/context-budget/index.js';
import * as checkpointStore from '../storage/checkpoint-store.js';
export async function handleContextBudget(args) {
    switch (args.action) {
        case 'status':
            return handleStatus(args.projectId);
        case 'configure':
            return handleConfigure(args);
        case 'checkpoint':
            return handleCheckpoint(args);
        case 'restore':
            return handleRestore(args.projectId, args.checkpointId);
        case 'list-checkpoints':
            return handleListCheckpoints(args.projectId, args.limit);
        case 'optimize':
            return handleOptimize(args.projectId);
        default:
            return {
                content: [
                    {
                        type: 'text',
                        text: ti('tools.context_budget.unknownAction', { action: String(args.action) }),
                    },
                ],
                isError: true,
            };
    }
}
async function handleStatus(projectId) {
    const stored = await checkpointStore.loadConfig(projectId);
    if (stored) {
        setConfig(stored);
    }
    const status = getStatus();
    const warning = getWarning();
    const lines = [
        t('tools.context_budget.statusHeading'),
        '',
        `| Metric | Value |`,
        `|--------|-------|`,
        `| Tokens used | ${String(status.tokensEstimatedUsed)} |`,
        `| Tokens available | ${String(status.tokensEstimatedAvailable)} |`,
        `| Usage | ${String(status.percentUsed)}% |`,
        `| Alert level | ${status.alertLevel} |`,
        `| Operations | ${String(status.operationCount)} |`,
    ];
    if (status.topConsumers.length > 0) {
        lines.push('', '### Top Consumers');
        for (const c of status.topConsumers) {
            lines.push(`- **${c.tool}**: ${String(c.tokens)} tokens`);
        }
    }
    if (warning) {
        lines.push('', `> **Warning**: ${warning.recommendation}`);
    }
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
async function handleConfigure(args) {
    const config = setConfig({
        ...(args.contextWindowSize !== undefined && { contextWindowSize: args.contextWindowSize }),
        ...(args.warningThreshold !== undefined && { warningThreshold: args.warningThreshold }),
        ...(args.criticalThreshold !== undefined && { criticalThreshold: args.criticalThreshold }),
    });
    await checkpointStore.saveConfig(args.projectId, config);
    return {
        content: [
            {
                type: 'text',
                text: ti('tools.context_budget.configuredMessage', {
                    windowSize: String(config.contextWindowSize),
                    warning: String(config.warningThreshold * 100),
                    critical: String(config.criticalThreshold * 100),
                }),
            },
        ],
    };
}
async function handleCheckpoint(args) {
    const status = getStatus();
    const cp = generateCheckpoint(args.projectId, status, {
        summary: args.summary,
        decisions: args.decisions,
        filesModified: args.filesModified,
        filesRead: args.filesRead,
        specsInProgress: args.specsInProgress,
        pendingWork: args.pendingWork,
    });
    const id = await checkpointStore.saveCheckpoint(args.projectId, cp);
    const formatted = formatCheckpoint(cp);
    return {
        content: [
            {
                type: 'text',
                text: `${ti('tools.context_budget.checkpointSaved', { id })}\n\n${formatted}`,
            },
        ],
    };
}
async function handleRestore(projectId, checkpointId) {
    const cp = await checkpointStore.loadCheckpoint(projectId, checkpointId);
    if (!cp) {
        return {
            content: [{ type: 'text', text: t('tools.context_budget.noCheckpointFound') }],
            isError: true,
        };
    }
    const formatted = formatCheckpoint(cp);
    return {
        content: [
            { type: 'text', text: `${t('tools.context_budget.restoredHeading')}\n\n${formatted}` },
        ],
    };
}
async function handleListCheckpoints(projectId, limit) {
    const summaries = await checkpointStore.listCheckpoints(projectId, limit ?? 10);
    if (summaries.length === 0) {
        return { content: [{ type: 'text', text: t('tools.context_budget.noCheckpoints') }] };
    }
    const lines = [t('tools.context_budget.listHeading'), ''];
    for (const s of summaries) {
        lines.push(`- **${s.id}** (${s.timestamp}): ${s.summary}`);
    }
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
function handleOptimize(projectId) {
    const ops = getSessionOps();
    const status = getStatus();
    const result = analyzeSession(ops, status);
    const lines = [
        ti('tools.context_budget.optimizeHeading', { projectId }),
        '',
        ti('tools.context_budget.currentUsage', {
            percent: String(result.currentUsage.percentUsed),
            level: result.currentUsage.alertLevel,
        }),
        '',
    ];
    if (result.delegationHints.length > 0) {
        lines.push(t('tools.context_budget.delegationHeading'));
        for (const hint of result.delegationHints) {
            lines.push(`- **${hint.operation}**: ${hint.reason} → use \`${hint.suggestedModel}\``);
        }
        lines.push('');
    }
    if (result.filesAlreadyRead.length > 5) {
        lines.push(t('tools.context_budget.batchReadHeading'));
        lines.push(t('tools.context_budget.batchReadHint'));
        lines.push('```');
        lines.push(suggestExplorePrompt(result.filesAlreadyRead));
        lines.push('```');
    }
    if (result.delegationHints.length === 0) {
        lines.push(t('tools.context_budget.noOptimizations'));
    }
    return Promise.resolve({ content: [{ type: 'text', text: lines.join('\n') }] });
}
//# sourceMappingURL=context-budget.js.map