/**
 * worktree-detect.mjs — git worktree detection (C29).
 *
 * Returns coordination-relevant info so locks can target the main repo's
 * .aperant/locks/ across worktrees. Keep the shape stable — project.mjs's
 * getSharedLockDir consumes it.
 */

import { execSync } from 'node:child_process'
import { resolve } from 'node:path'

/**
 * Detect if we're inside a git worktree and return coordination-relevant info.
 * This prevents worktree-in-worktree nesting and ensures locks coordinate
 * across worktrees by using the git common dir.
 */
export function detectWorktree(projectDir) {
	const targetDir = resolve(projectDir)
	try {
		const gitDir = execSync('git rev-parse --git-dir 2>/dev/null', {
			cwd: targetDir,
			encoding: 'utf-8',
		}).trim()
		const gitCommonDir = execSync('git rev-parse --git-common-dir 2>/dev/null', {
			cwd: targetDir,
			encoding: 'utf-8',
		}).trim()
		const topLevel = execSync('git rev-parse --show-toplevel 2>/dev/null', {
			cwd: targetDir,
			encoding: 'utf-8',
		}).trim()

		// If git-dir !== git-common-dir, we're in a worktree
		const isWorktree = resolve(targetDir, gitDir) !== resolve(targetDir, gitCommonDir)

		// Main repo root is the parent of git-common-dir (which is <main>/.git)
		const mainRepoRoot = isWorktree ? resolve(resolve(targetDir, gitCommonDir), '..') : topLevel

		return {
			is_worktree: isWorktree,
			git_dir: resolve(targetDir, gitDir),
			git_common_dir: resolve(targetDir, gitCommonDir),
			worktree_root: topLevel,
			main_repo_root: mainRepoRoot,
		}
	} catch {
		return {
			is_worktree: false,
			git_dir: null,
			git_common_dir: null,
			worktree_root: null,
			main_repo_root: null,
		}
	}
}
