/**
 * Pure SF health widget logic.
 *
 * Separates project-state detection and line rendering from the widget's
 * runtime integrations so the regressions can be tested directly.
 */
import { existsSync } from "node:fs";
import { detectProjectState } from "./detection.js";
import { sfRoot } from "./paths.js";
export function detectHealthWidgetProjectState(basePath) {
	if (!existsSync(sfRoot(basePath))) return "none";
	const { state } = detectProjectState(basePath);
	return state === "v2-sf" ? "active" : "initialized";
}
function formatCost(n) {
	return n >= 1 ? `$${n.toFixed(2)}` : `${(n * 100).toFixed(1)}¢`;
}
/**
 * Format Unix epoch (seconds) as human-readable relative time.
 * Returns "just now", "Xm ago", "Xh ago", or "Xd ago".
 */
export function formatRelativeTime(epochSeconds) {
	const diffSeconds = Math.floor(Date.now() / 1000) - epochSeconds;
	if (diffSeconds < 60) return "just now";
	const minutes = Math.floor(diffSeconds / 60);
	if (minutes < 60) return `${minutes}m ago`;
	const hours = Math.floor(minutes / 60);
	if (hours < 24) return `${hours}h ago`;
	const days = Math.floor(hours / 24);
	return `${days}d ago`;
}
/**
 * Truncate a commit message to fit the widget, appending "…" if needed.
 */
function truncateMessage(msg, maxLen) {
	if (msg.length <= maxLen) return msg;
	return msg.slice(0, maxLen - 1) + "…";
}
/**
 * Build compact health lines for the widget.
 * Returns a string array suitable for setWidget().
 */
export function buildHealthLines(data) {
	if (data.projectState === "none") {
		return ["  SF  No project loaded — run /next to start"];
	}
	if (data.projectState === "initialized") {
		return ["  SF  Project initialized — run /next to continue setup"];
	}
	const parts = [];
	const totalIssues =
		data.environmentErrorCount +
		data.environmentWarningCount +
		(data.providerIssue ? 1 : 0);
	if (totalIssues === 0) {
		parts.push("● System OK");
	} else if (
		data.environmentErrorCount > 0 ||
		data.providerIssue?.includes("✗")
	) {
		parts.push(`✗ ${totalIssues} issue${totalIssues > 1 ? "s" : ""}`);
	} else {
		parts.push(`⚠ ${totalIssues} warning${totalIssues > 1 ? "s" : ""}`);
	}
	if (data.budgetCeiling !== undefined && data.budgetCeiling > 0) {
		const pct = Math.min(100, (data.budgetSpent / data.budgetCeiling) * 100);
		parts.push(
			`Budget: ${formatCost(data.budgetSpent)}/${formatCost(data.budgetCeiling)} (${pct.toFixed(0)}%)`,
		);
	} else if (data.budgetSpent > 0) {
		parts.push(`Spent: ${formatCost(data.budgetSpent)}`);
	}
	if (data.providerIssue) {
		parts.push(data.providerIssue);
	}
	if (data.environmentErrorCount > 0) {
		parts.push(
			`Env: ${data.environmentErrorCount} error${data.environmentErrorCount > 1 ? "s" : ""}`,
		);
	} else if (data.environmentWarningCount > 0) {
		parts.push(
			`Env: ${data.environmentWarningCount} warning${data.environmentWarningCount > 1 ? "s" : ""}`,
		);
	}
	// Always-on last commit display — shows relative time + truncated message
	if (data.lastCommitEpoch !== null && data.lastCommitEpoch > 0) {
		const relTime = formatRelativeTime(data.lastCommitEpoch);
		const msg = data.lastCommitMessage
			? ` — ${truncateMessage(data.lastCommitMessage, 50)}`
			: "";
		parts.push(`Last commit: ${relTime}${msg}`);
	}
	// Suggest remote questions if not configured (helps autonomous mode users)
	if (data.projectState === "active" && !data.remoteQuestionsConfigured) {
		parts.push("/remote telegram");
	}
	return [`  ${parts.join("  │  ")}`];
}
