/**
 * Cost command handler — unified cost query surface.
 *
 * Purpose: provide session-scoped and historical cost queries
 * from both the legacy metrics ledger and the new metrics-central DB table.
 *
 * Consumer: /cost CLI command.
 */
import { formatCost, getLedger, loadLedgerFromDisk } from "./metrics.js";
import { queryMetrics } from "./metrics-central.js";

export async function handleCost(args, ctx, basePath) {
	const showSession = args.includes("--session");
	const showAll = args.includes("--all");
	const showPrometheus = args.includes("--prometheus");

	// Try metrics-central DB first (queryMetrics uses its own metrics.db connection)
	if (showSession || showAll) {
		const sessionId = showSession ? extractSessionId() : null;
		const rows = queryMetrics(null, sessionId, "sf_cost_total", 1000);
		if (rows.length > 0) {
			const totalCost = rows.reduce((sum, r) => sum + (r.value || 0), 0);
			const lines = [
				`Cost from metrics-central (${rows.length} records):`,
				`  Total: ${formatCost(totalCost)}`,
				"",
				"By unit:",
			];
			for (const row of rows.slice(0, 20)) {
				const labels = JSON.parse(row.labels || "{}");
				lines.push(
					`  ${labels.unit_id || "?"}: ${formatCost(row.value)} (${labels.model_id || "?"})`,
				);
			}
			ctx.ui.notify(lines.join("\n"), "info");
			return;
		}
	}

	// Fall back to legacy metrics ledger
	const ledger = getLedger() || loadLedgerFromDisk(basePath);
	if (!ledger || ledger.units.length === 0) {
		ctx.ui.notify("No cost data — no units have been executed yet.", "info");
		return;
	}

	const totals = ledger.units.reduce(
		(acc, u) => {
			acc.cost += u.cost;
			acc.tokens += u.tokens.total;
			acc.units++;
			return acc;
		},
		{ cost: 0, tokens: 0, units: 0 },
	);

	const lines = [
		`Project cost summary (${totals.units} units):`,
		`  Total cost: ${formatCost(totals.cost)}`,
		`  Total tokens: ${totals.tokens.toLocaleString()}`,
	];

	if (showPrometheus) {
		const { getMetricsText } = await import("./metrics-central.js");
		const promText = getMetricsText();
		lines.push("", "Prometheus metrics:", promText.slice(0, 2000));
	}

	ctx.ui.notify(lines.join("\n"), "info");
}

function extractSessionId() {
	// Best-effort: try to get session from AutoSession
	try {
		const { getAutoSession } = require("./auto/session.js");
		return getAutoSession()?.currentTraceId || null;
	} catch {
		return null;
	}
}
