import path from "path";
import fs from "fs";
//#region src/core/usage.ts
const DEFAULT_PRICING = {
	"claude-haiku-4-5": {
		input: 1,
		output: 5
	},
	default: {
		input: 1,
		output: 5
	}
};
function ledgerPath(dataDir) {
	return path.join(dataDir, ".agentic", "usage.ndjson");
}
function loadPricing(dataDir) {
	const p = path.join(dataDir, ".agentic", "llm-pricing.json");
	if (!fs.existsSync(p)) return DEFAULT_PRICING;
	try {
		const custom = JSON.parse(fs.readFileSync(p, "utf-8"));
		return {
			...DEFAULT_PRICING,
			...custom
		};
	} catch {
		return DEFAULT_PRICING;
	}
}
function computeCost(pricing, model, inputTokens, outputTokens) {
	const price = pricing[model] ?? pricing["default"];
	const cost = inputTokens / 1e6 * price.input + outputTokens / 1e6 * price.output;
	return Math.round(cost * 1e6) / 1e6;
}
function recordUsage(dataDir, u) {
	const entry = {
		timestamp: (/* @__PURE__ */ new Date()).toISOString(),
		...u.slug ? { slug: u.slug } : {},
		...u.tool ? { tool: u.tool } : {},
		model: u.model,
		inputTokens: u.inputTokens,
		outputTokens: u.outputTokens,
		costUsd: computeCost(loadPricing(dataDir), u.model, u.inputTokens, u.outputTokens)
	};
	const p = ledgerPath(dataDir);
	try {
		fs.mkdirSync(path.dirname(p), { recursive: true });
		fs.appendFileSync(p, JSON.stringify(entry) + "\n", "utf-8");
	} catch {}
}
function loadUsage(dataDir) {
	const p = ledgerPath(dataDir);
	if (!fs.existsSync(p)) return [];
	return fs.readFileSync(p, "utf-8").split("\n").filter(Boolean).flatMap((line) => {
		try {
			return [JSON.parse(line)];
		} catch {
			return [];
		}
	});
}
function aggregateUsage(dataDir, opts = {}) {
	const agg = {
		totalInputTokens: 0,
		totalOutputTokens: 0,
		totalCostUsd: 0,
		calls: 0,
		bySlug: {}
	};
	for (const e of loadUsage(dataDir)) {
		if (opts.slug && e.slug !== opts.slug) continue;
		agg.totalInputTokens += e.inputTokens;
		agg.totalOutputTokens += e.outputTokens;
		agg.totalCostUsd += e.costUsd;
		agg.calls++;
		const key = e.slug ?? "(unattributed)";
		const b = agg.bySlug[key] ?? {
			inputTokens: 0,
			outputTokens: 0,
			costUsd: 0,
			calls: 0
		};
		b.inputTokens += e.inputTokens;
		b.outputTokens += e.outputTokens;
		b.costUsd += e.costUsd;
		b.calls++;
		agg.bySlug[key] = b;
	}
	agg.totalCostUsd = Math.round(agg.totalCostUsd * 1e6) / 1e6;
	return agg;
}
//#endregion
export { aggregateUsage, recordUsage };

//# sourceMappingURL=usage-BVlFlKW_.js.map