/**
 * worktree-session-state.js — Shared mutable state for the active worktree session.
 *
 * Purpose: isolate the originalCwd tracking variable so it can be read by other
 * worktree modules (auto-worktree, worktree-root, etc.) without importing the full
 * worktree-command.js command handler.
 *
 * Consumer: worktree-command.js (primary owner), any module that needs
 * getActiveWorktreeName() or getWorktreeOriginalCwd() without the command handler.
 */
import { basename, join, normalize, sep } from "node:path";

let originalCwd = null;
/** Return the original project root if currently in a worktree, or null. */
export function getWorktreeOriginalCwd() {
	return originalCwd;
}
/** Set the original project root when entering a worktree. */
export function setWorktreeOriginalCwd(cwd) {
	originalCwd = cwd;
}
/** Clear the stored root when returning from a worktree. */
export function clearWorktreeOriginalCwd() {
	originalCwd = null;
}
/**
 * Detect and set originalCwd from the current process path if not already set.
 * Used during /reload recovery when process.cwd() is still inside a worktree but
 * the module-level variable was reset.
 */
export function ensureWorktreeOriginalCwdFromPath(cwd = process.cwd()) {
	if (originalCwd) return originalCwd;
	const marker = `${sep}.sf${sep}worktrees${sep}`;
	const markerIdx = cwd.indexOf(marker);
	if (markerIdx !== -1) {
		originalCwd = cwd.slice(0, markerIdx);
	}
	return originalCwd;
}
/**
 * Return the name of the active worktree, or null if not in one.
 * Extracts the first path segment after .sf/worktrees/ using normalize to handle
 * both separators correctly.
 */
export function getActiveWorktreeName() {
	if (!originalCwd) return null;
	const cwd = normalize(process.cwd());
	const wtDir = normalize(join(originalCwd, ".sf", "worktrees"));
	if (!cwd.startsWith(wtDir)) return null;
	const rel = cwd.slice(wtDir.length).replace(/^[\\/]+/, "");
	const name = basename(rel.split(/[\\/]/)[0] ?? rel);
	return name || null;
}
