/**
 * project.mjs — project-root + shared-lock-dir helpers (C29).
 *
 * As of subtask 03 `detectWorktree` lives in `src/cli/git/worktree-detect.mjs`
 * so this module imports it directly. Earlier call sites that passed the
 * detector as an explicit argument no longer need to — callers can invoke
 * `getSharedLockDir(projectDir)` with a single argument.
 */

import { existsSync, mkdirSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { detectWorktree } from '../git/worktree-detect.mjs'

/**
 * Walk upward from the target path until we find a `.aperant/` directory.
 * Returns the containing project root, or null if none is found within
 * 8 parent levels.
 */
export function findProjectRootFromPath(filePath) {
	let cur = resolve(filePath)
	for (let i = 0; i < 8; i++) {
		const parent = dirname(cur)
		if (parent === cur) return null
		if (existsSync(join(parent, '.aperant'))) return parent
		cur = parent
	}
	return null
}

/**
 * Get the shared lock directory — uses git common dir so locks coordinate
 * across worktrees. Falls back to local .aperant/locks/ if not in git.
 */
export function getSharedLockDir(projectDir) {
	const wt = detectWorktree(projectDir)
	if (wt.is_worktree && wt.main_repo_root) {
		// Use main repo's .aperant/locks/ so all worktrees share the same locks
		const sharedDir = join(wt.main_repo_root, '.aperant', 'locks')
		mkdirSync(sharedDir, { recursive: true })
		return sharedDir
	}
	// Not a worktree — use local
	const localDir = join(resolve(projectDir), '.aperant', 'locks')
	mkdirSync(localDir, { recursive: true })
	return localDir
}
