/**
 * Thin worktree-detection helpers with no intra-repo imports.
 *
 * Extracted from worktree.js so that git-service.js can import
 * detectWorktreeName without pulling in the full worktree module
 * (which in turn imports GitService from git-service.js, creating
 * a cycle).  worktree.js re-exports both symbols for back-compat.
 *
 * Purpose: provide a zero-dependency path for detecting whether a
 * basePath lives inside a SF worktree (.sf/worktrees/<name>).
 */

/**
 * Locate the worktree segment within a normalized path string.
 * Returns the string indices needed by detectWorktreeName and
 * resolveProjectRoot; returns null if not inside a SF worktree.
 *
 * @param {string} normalizedPath — forward-slash-normalised absolute path.
 */
function findWorktreeSegment(normalizedPath) {
	// Direct layout: /.sf/worktrees/<name>
	const directMarker = "/.sf/worktrees/";
	const idx = normalizedPath.indexOf(directMarker);
	if (idx !== -1) {
		return { sfIdx: idx, afterWorktrees: idx + directMarker.length };
	}
	// Symlink-resolved layout: /.sf/projects/<hash>/worktrees/<name>
	const symlinkRe = /\/\.sf\/projects\/[a-f0-9]+\/worktrees\//;
	const match = normalizedPath.match(symlinkRe);
	if (match && match.index !== undefined) {
		return {
			sfIdx: match.index,
			afterWorktrees: match.index + match[0].length,
		};
	}
	return null;
}

/**
 * Detect the active worktree name from the current working directory.
 * Returns null if not inside a SF worktree (.sf/worktrees/<name>/).
 *
 * Consumer: git-service.js (GitService.getTargetBranch) and worktree.js.
 *
 * @param {string} basePath
 * @returns {string | null}
 */
export function detectWorktreeName(basePath) {
	const normalizedPath = basePath.replaceAll("\\", "/");
	const seg = findWorktreeSegment(normalizedPath);
	if (!seg) return null;
	const afterMarker = normalizedPath.slice(seg.afterWorktrees);
	const name = afterMarker.split("/")[0];
	return name || null;
}

export { findWorktreeSegment };
