import { j as theme } from "./registry-Sbac4a4z.js";
import "./paths-By0XjHBk.js";
import "./utils-CTPsqyE_.js";
import "./subsystem-CHbO_DkH.js";
import "./exec-DuYbft0z.js";
import "./agent-scope-DOrZjOnW.js";
import "./model-selection-7wdmO-Iw.js";
import { i as loadConfig } from "./config-B4jkreCN.js";
import "./boolean-CbZoNRMn.js";
import "./env-BRnPI9sO.js";
import "./shell-env-Dc3iU7HK.js";
import "./manifest-registry-D1MLZEjS.js";
import "./paths-BtvQ7JvU.js";
import "./session-cost-usage-D3mgssM_.js";
import { i as resolveWindow, n as formatSummaryReport, r as loadCostBenchmarkSummary, t as buildCostBreakdown } from "./breakdown-B_Dhhm3K.js";

//#region src/cli/cost-cli.ts
function registerCostCli(program) {
	const cost = program.command("cost").description("Inspect token + GPU cost estimates for self-hosted models").action(() => {
		cost.help({ error: true });
	});
	cost.command("detect [provider]").description("Probe a self-hosted serving endpoint and infer GPU + hourly rate").option("--json", "Output JSON", false).option("--timeout <ms>", "Probe timeout in milliseconds", "4000").option("--force", "Bypass the 60s probe cache and re-probe", false).option("--input <tokens>", "Sample input token count for cost estimate").option("--output <tokens>", "Sample output token count for cost estimate").action(async (providerArg, opts) => {
		const cfg = loadConfig();
		const providers = cfg.models?.providers ?? {};
		const targets = providerArg ? [providerArg] : Object.entries(providers).filter(([, p]) => typeof p?.baseUrl === "string" && p.baseUrl.trim()).map(([id]) => id);
		if (targets.length === 0) {
			if (opts.json) process.stdout.write(`${JSON.stringify({ probes: [] })}\n`);
			else process.stdout.write("No providers with baseUrl configured.\n");
			return;
		}
		const timeoutMs = Number.parseInt(opts.timeout ?? "4000", 10);
		const usage = opts.input !== void 0 || opts.output !== void 0 ? {
			input: opts.input !== void 0 ? Number.parseInt(opts.input, 10) : void 0,
			output: opts.output !== void 0 ? Number.parseInt(opts.output, 10) : void 0
		} : void 0;
		const probes = [];
		for (const id of targets) {
			const baseUrl = providers[id]?.baseUrl ?? "";
			const modelId = providers[id]?.models?.[0]?.id;
			const breakdown = await buildCostBreakdown({
				baseUrl,
				provider: id,
				modelId,
				config: cfg,
				probeTimeoutMs: timeoutMs,
				forceProbeRefresh: Boolean(opts.force),
				usage
			});
			probes.push({
				provider: id,
				baseUrl,
				breakdown
			});
		}
		if (opts.json) {
			process.stdout.write(`${JSON.stringify({ probes }, null, 2)}\n`);
			return;
		}
		for (const probe of probes) {
			const header = theme.heading(probe.provider);
			process.stdout.write(`${header}\n`);
			process.stdout.write(`  baseUrl: ${probe.baseUrl || theme.muted("(none)")}\n`);
			renderBreakdown(probe.breakdown);
			process.stdout.write("\n");
		}
	});
	cost.command("summary").description("Show cumulative token/cost totals and Claude benchmark comparison").option("--window <span>", "today | week | month | all", "week").option("--json", "Output JSON", false).option("--agent <id>", "Agent id (defaults to active agent)").action(async (opts) => {
		const cfg = loadConfig();
		const window = opts.window ?? "week";
		if (window !== "today" && window !== "week" && window !== "month" && window !== "all") {
			process.stderr.write(`Unknown window '${opts.window}' — use today | week | month | all\n`);
			process.exitCode = 2;
			return;
		}
		const { startMs, endMs } = resolveWindow(window);
		const summary = await loadCostBenchmarkSummary({
			startMs,
			endMs,
			config: cfg,
			agentId: opts.agent
		});
		if (opts.json) {
			process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`);
			return;
		}
		const label = `${window.charAt(0).toUpperCase()}${window.slice(1)}`;
		process.stdout.write(`${formatSummaryReport(summary, label)}\n`);
	});
}
function renderBreakdown(b) {
	if (b.serving) {
		const v = b.serving.version ? ` ${b.serving.version}` : "";
		process.stdout.write(`  engine:  ${b.serving.engine}${v}\n`);
		if (b.serving.modelId) process.stdout.write(`  model:   ${b.serving.modelId}\n`);
		if (b.serving.contextWindow !== void 0) process.stdout.write(`  context: ${b.serving.contextWindow}\n`);
		if (b.serving.observedTps !== void 0) process.stdout.write(`  tps:     ${b.serving.observedTps.toFixed(1)} (last interval)\n`);
		if (b.serving.kvCacheUsagePerc !== void 0) process.stdout.write(`  kv:      ${(b.serving.kvCacheUsagePerc * 100).toFixed(1)}%\n`);
		if (b.serving.queueDepth !== void 0) process.stdout.write(`  queue:   ${b.serving.queueDepth}\n`);
		if (b.serving.numRequestsRunning !== void 0) process.stdout.write(`  running: ${b.serving.numRequestsRunning}\n`);
		if (b.serving.cacheConfig) {
			const cc = b.serving.cacheConfig;
			const bits = [
				cc.cacheDtype && `dtype=${cc.cacheDtype}`,
				cc.blockSize !== void 0 && `block=${cc.blockSize}`,
				cc.numGpuBlocks !== void 0 && `blocks=${cc.numGpuBlocks}`,
				cc.gpuMemoryUtilization !== void 0 && `gpu_mem_util=${cc.gpuMemoryUtilization}`,
				cc.enablePrefixCaching !== void 0 && `prefix_cache=${cc.enablePrefixCaching ? "on" : "off"}`
			].filter(Boolean);
			if (bits.length) process.stdout.write(`  cache:   ${bits.join(" ")}\n`);
		}
	} else process.stdout.write(`  ${theme.muted("probe returned nothing (unreachable or hosted)")}\n`);
	if (b.gpu?.gpuType) {
		process.stdout.write(`  gpu:     ${b.gpu.gpuCount}× ${b.gpu.gpuType} (${b.gpu.confidence}-confidence)\n`);
		if (b.gpu.paramsB !== void 0) {
			const bpp = b.gpu.bytesPerParam ?? 2;
			process.stdout.write(`           model=${b.gpu.paramsB}B × ${bpp} byte/param ≈ ${(b.gpu.paramsB * bpp).toFixed(0)}GB\n`);
		}
	} else process.stdout.write(`  gpu:     ${theme.muted("not inferred (no signal in URL)")}\n`);
	if (b.hourlyRate !== void 0) {
		const total = b.hourlyRate * (b.gpu?.gpuCount ?? 1);
		process.stdout.write(`  rate:    $${b.hourlyRate.toFixed(2)}/hr/GPU · $${total.toFixed(2)}/hr total · ${b.hourlyRateSource}\n`);
	} else process.stdout.write(`  rate:    ${theme.muted("no rate (configure cost.hourlyRate or set models.gpuRates)")}\n`);
	if (b.decodeTps !== void 0 && b.prefillTps !== void 0) process.stdout.write(`  tput:    ${b.decodeTps.toFixed(0)} decode · ${b.prefillTps.toFixed(0)} prefill (${b.throughputSource})\n`);
	if (b.instanceCostUsd !== void 0) {
		const perTok = b.perTokenAvgUsd ? ` · avg $${(b.perTokenAvgUsd * 1e6).toFixed(2)}/M tokens` : "";
		process.stdout.write(`  est:     $${b.instanceCostUsd.toFixed(4)}${perTok}\n`);
	}
	if (b.benchmarks.length > 0) {
		process.stdout.write(`  bench:   ${b.benchmarkTarget}\n`);
		for (const bm of b.benchmarks) process.stdout.write(`    ${bm.tier.padEnd(6)} $${bm.costUsd.toFixed(4)}\n`);
		if (b.costLineSuffix) process.stdout.write(`  suffix:  ${b.costLineSuffix}\n`);
	}
	if (b.engineLine) process.stdout.write(`  status:  ${b.engineLine}\n`);
	if (b.hardwareLine) process.stdout.write(`  hw:      ${b.hardwareLine}\n`);
}

//#endregion
export { registerCostCli };