/**
 * Trajectory Command — /trajectory handler for SF.
 *
 * Purpose: Display step-by-step execution trace with costs, errors,
 * and tool usage for the current session or a specific unit.
 *
 * Consumer: ops.js command dispatcher.
 */

import { getDatabase, isDbAvailable } from "./sf-db.js";
import {
	formatTrajectory,
	getTrajectory,
	getTrajectorySummary,
} from "./trajectory-recorder.js";

/**
 * Handle the /trajectory command.
 *
 * @param {string} args — command arguments
 * @param {object} ctx — command context
 * @param {string} basePath — project root
 */
export async function handleTrajectory(args, ctx, basePath) {
	if (!isDbAvailable()) {
		ctx.ui.notify(
			"Trajectory recording requires a database connection.",
			"warning",
		);
		return;
	}

	const db = getDatabase();
	// Resolve session from basePath-scoped DB or fall back to context
	const sessionId = basePath
		? `${basePath}-session`
		: ctx.sessionManager?.getSessionId?.() || "default";

	// Parse flags
	const flags = args.split(/\s+/).filter(Boolean);
	const showAll = flags.includes("--all");
	const showErrors = flags.includes("--errors");
	const showTools = flags.includes("--tools");
	const showLLM = flags.includes("--llm");
	const limit = flags.find((f) => f.startsWith("--limit="))
		? parseInt(flags.find((f) => f.startsWith("--limit=")).split("=")[1], 10)
		: 50;

	// Get trajectory steps
	const filter = {};
	if (showErrors) filter.stepType = "error";
	else if (showTools) filter.stepType = "tool_call";
	else if (showLLM) filter.stepType = "llm_call";

	const steps = getTrajectory({
		sessionId: showAll ? undefined : sessionId,
		...filter,
		limit,
		db,
	});

	if (steps.length === 0) {
		ctx.ui.notify("No trajectory steps recorded yet.", "info");
		return;
	}

	// Get summary
	const summary = getTrajectorySummary(sessionId, null, db);

	// Build output
	const lines = [];
	lines.push(`Trajectory for session ${sessionId.slice(0, 8)}`);

	if (summary) {
		lines.push(
			`Steps: ${summary.totalSteps} | Errors: ${summary.errorCount} | ` +
				`Tokens: ${summary.totalInputTokens + summary.totalOutputTokens} | ` +
				`Cost: $${summary.totalCost.toFixed(4)} | Tools: ${summary.uniqueTools}`,
		);
	}

	lines.push("");
	lines.push(formatTrajectory(steps, { maxSteps: limit }));

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