import { showNextAction } from "../../shared/tui.js";
import { validateDirectory } from "../validate-directory.js";
import { resolveProjectRoot } from "../worktree.js";
/**
 * Typed error for when SF is run outside a valid project directory.
 * Command handlers catch this to show a friendly message instead of a raw exception.
 */
export class SFNoProjectError extends Error {
	constructor(reason) {
		super(reason);
		this.name = "SFNoProjectError";
	}
}
export function projectRoot() {
	let cwd;
	try {
		cwd = process.cwd();
	} catch {
		// cwd directory was deleted (e.g. worktree teardown) — fall back to HOME (#3598)
		cwd = process.env.HOME ?? "/";
	}
	const root = resolveProjectRoot(cwd);
	const pathToCheck = root !== cwd ? cwd : root;
	const result = validateDirectory(pathToCheck);
	if (result.severity === "blocked") {
		throw new SFNoProjectError(
			result.reason ?? "SF must be run inside a project directory.",
		);
	}
	return root;
}
export async function guardRemoteSession(ctx, _pi) {
	const { checkRemoteAutoSession, isAutoActive, isAutoPaused, stopAutoRemote } =
		await import("../auto.js");
	const { handleStatus } = await import("./handlers/core.js");
	if (isAutoActive() || isAutoPaused()) return true;
	const remote = checkRemoteAutoSession(projectRoot());
	if (!remote.running || !remote.pid) return true;
	const unitLabel =
		remote.unitType && remote.unitId
			? `${remote.unitType} (${remote.unitId})`
			: "unknown unit";
	// In RPC/web bridge mode, interactive TUI prompts (showNextAction) block
	// forever because there is no terminal to answer them. Notify and bail.
	if (process.env.SF_WEB_BRIDGE_TUI === "1") {
		ctx.ui.notify(
			`Another autonomous mode session (PID ${remote.pid}) is running on this project (${unitLabel}). ` +
				`Stop it first with /autonomous stop, or use /steer to redirect it.`,
			"warning",
		);
		return false;
	}
	const choice = await showNextAction(ctx, {
		title: `Autonomous mode is running in another terminal (PID ${remote.pid})`,
		summary: [
			`Currently executing: ${unitLabel}`,
			...(remote.startedAt ? [`Started: ${remote.startedAt}`] : []),
		],
		actions: [
			{
				id: "status",
				label: "View status",
				description: "Show the current SF progress dashboard.",
				recommended: true,
			},
			{
				id: "steer",
				label: "Steer the session",
				description:
					"Use /steer <instruction> to redirect the running session.",
			},
			{
				id: "stop",
				label: "Stop remote session",
				description: `Send SIGTERM to PID ${remote.pid} to stop it gracefully.`,
			},
			{
				id: "force",
				label: "Force start (steal lock)",
				description: "Start a new session, terminating the existing one.",
			},
		],
		notYetMessage: "Run /next when ready.",
	});
	if (choice === "status") {
		await handleStatus(ctx);
		return false;
	}
	if (choice === "steer") {
		ctx.ui.notify(
			"Use /steer <instruction> to redirect the running autonomous mode session.\n" +
				"Example: /steer Use Postgres instead of SQLite",
			"info",
		);
		return false;
	}
	if (choice === "stop") {
		const result = stopAutoRemote(projectRoot());
		if (result.found) {
			ctx.ui.notify(
				`Sent stop signal to autonomous mode session (PID ${result.pid}). It will shut down gracefully.`,
				"info",
			);
		} else if (result.error) {
			ctx.ui.notify(
				`Failed to stop remote autonomous run: ${result.error}`,
				"error",
			);
		} else {
			ctx.ui.notify("Remote session is no longer running.", "info");
		}
		return false;
	}
	return choice === "force";
}
