/**
 * budget.mjs — token-budget path/estimation/status helpers (C29).
 */

import { existsSync, readFileSync } from 'node:fs'
import { join, resolve } from 'node:path'

export const DEFAULT_BUDGET_LIMIT = 400000
export const BUDGET_WARN_50 = 0.5
export const BUDGET_WARN_80 = 0.8

export function taskBudgetPath(targetDir, taskId) {
	return join(resolve(targetDir), '.aperant', 'tasks', taskId, 'budget.json')
}

export function estimateTokens(text) {
	if (typeof text !== 'string' || text.length === 0) return 0
	return Math.ceil(text.length / 4)
}

export function readBudget(path) {
	if (!existsSync(path)) return null
	try {
		return JSON.parse(readFileSync(path, 'utf-8'))
	} catch {
		return null
	}
}

export function budgetStatusFromTotal(total, limit) {
	if (total >= limit) return 'exceeded'
	if (total >= limit * BUDGET_WARN_80) return 'warning_80'
	if (total >= limit * BUDGET_WARN_50) return 'warning_50'
	return 'ok'
}
