/**
 * commands/token-budget.mjs — token-budget init/record/check command (C29).
 */
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
import { dirname } from 'node:path';
import { budgetStatusFromTotal, DEFAULT_BUDGET_LIMIT, estimateTokens, readBudget, taskBudgetPath, } from '../budget/budget.mjs';
import { withFileLock } from '../util/fs-lock.mjs';
import { atomicWriteJson } from '../util/io.mjs';
import { err, ok } from '../util/result.mjs';
export function cmdTokenBudget(args, targetDir) {
    const action = args[0];
    if (!action) {
        return err('Usage: apt-tools token-budget <init|record|check> [flags]');
    }
    const flag = (name) => {
        const i = args.indexOf(name);
        return i >= 0 ? args[i + 1] : null;
    };
    const taskId = flag('--task-id');
    if (!taskId)
        return err('--task-id is required');
    const budgetPath = taskBudgetPath(targetDir, taskId);
    mkdirSync(dirname(budgetPath), { recursive: true });
    if (action === 'init') {
        const limit = parseInt(flag('--limit') || String(DEFAULT_BUDGET_LIMIT), 10);
        withFileLock(budgetPath, () => {
            atomicWriteJson(budgetPath, {
                task_id: taskId,
                limit_tokens: limit,
                consumed: {},
                total: 0,
                warnings: [],
                status: 'ok',
                created_at: new Date().toISOString(),
            });
        });
        return ok({
            status: 'ok',
            command: 'token-budget',
            action: 'init',
            task_id: taskId,
            limit_tokens: limit,
        });
    }
    if (action === 'record') {
        const phase = flag('--phase') || 'unknown';
        const tokensFlag = flag('--tokens');
        const textFlag = flag('--text-file');
        let tokens = 0;
        if (tokensFlag) {
            tokens = parseInt(tokensFlag, 10) || 0;
        }
        else if (textFlag && existsSync(textFlag)) {
            tokens = estimateTokens(readFileSync(textFlag, 'utf-8'));
        }
        if (tokens <= 0)
            return err('Provide --tokens N or --text-file <path>');
        let result;
        withFileLock(budgetPath, () => {
            const current = readBudget(budgetPath) || {
                task_id: taskId,
                limit_tokens: DEFAULT_BUDGET_LIMIT,
                consumed: {},
                total: 0,
                warnings: [],
                status: 'ok',
            };
            current.consumed[phase] = (current.consumed[phase] || 0) + tokens;
            current.total = (current.total || 0) + tokens;
            const previousStatus = current.status;
            current.status = budgetStatusFromTotal(current.total, current.limit_tokens);
            if (current.status !== previousStatus && current.status !== 'ok') {
                current.warnings.push({
                    phase,
                    at: current.total,
                    status: current.status,
                    ts: new Date().toISOString(),
                });
            }
            atomicWriteJson(budgetPath, current);
            result = current;
        });
        return ok({
            status: 'ok',
            command: 'token-budget',
            action: 'record',
            task_id: taskId,
            phase,
            added_tokens: tokens,
            total: result.total,
            limit_tokens: result.limit_tokens,
            budget_status: result.status,
        });
    }
    if (action === 'check') {
        const current = readBudget(budgetPath);
        if (!current) {
            return ok({
                status: 'ok',
                command: 'token-budget',
                action: 'check',
                task_id: taskId,
                exists: false,
            });
        }
        return ok({
            status: 'ok',
            command: 'token-budget',
            action: 'check',
            task_id: taskId,
            exists: true,
            total: current.total,
            limit_tokens: current.limit_tokens,
            consumed: current.consumed,
            warnings: current.warnings,
            budget_status: current.status,
            exceeded: current.status === 'exceeded',
        });
    }
    return err(`Unknown token-budget action: ${action}`);
}
//# sourceMappingURL=token-budget.mjs.map