"""Path derivation for Legionnaire worktrees and directories."""

import subprocess
from pathlib import Path


class NotInGitRepoError(Exception):
    """Raised when not in a git repository."""

    pass


def get_repo_root(repo_hint: Path | None = None) -> Path:
    """Get the root directory of the git repository.

    Args:
        repo_hint: Optional path to start the search from. If None, uses cwd.

    Returns:
        The absolute path to the repository root.

    Raises:
        NotInGitRepoError: If the path is not inside a git repository.
    """
    cwd = repo_hint or Path.cwd()
    try:
        result = subprocess.run(
            ["git", "rev-parse", "--show-toplevel"],
            cwd=cwd,
            check=True,
            capture_output=True,
            text=True,
        )
        return Path(result.stdout.strip())
    except subprocess.CalledProcessError as e:
        raise NotInGitRepoError(f"Not in a git repository: {cwd}") from e


def get_worktrees_root(repo_root: Path) -> Path:
    """Get the worktrees root directory for a repository.

    The worktrees root is a sibling of the repo root, named {repo_name}_worktrees.

    Args:
        repo_root: The path to the repository root.

    Returns:
        The path to the worktrees root directory.
    """
    return repo_root.parent / f"{repo_root.name}_worktrees"


def parent_dir(worktrees_root: Path, parent_id: str) -> Path:
    """Get the directory containing the parent worktree and its children.

    Args:
        worktrees_root: The worktrees root directory.
        parent_id: The parent ID (may contain '/' for nesting).

    Returns:
        The path to the parent directory.
    """
    return worktrees_root / parent_id


def parent_worktree_path(worktrees_root: Path, parent_id: str) -> Path:
    """Get the path to the parent worktree.

    Args:
        worktrees_root: The worktrees root directory.
        parent_id: The parent ID.

    Returns:
        The path to the parent worktree (ends in /parent).
    """
    return parent_dir(worktrees_root, parent_id) / "parent"


def child_worktree_path(worktrees_root: Path, parent_id: str, child_id: str) -> Path:
    """Get the path to a child worktree.

    Args:
        worktrees_root: The worktrees root directory.
        parent_id: The parent ID.
        child_id: The child ID.

    Returns:
        The path to the child worktree.
    """
    return parent_dir(worktrees_root, parent_id) / child_id


def parent_branch_name(parent_id: str) -> str:
    """Get the branch name for a parent.

    Args:
        parent_id: The parent ID.

    Returns:
        The branch name (parent_id/parent).
    """
    return f"{parent_id}/parent"


def child_branch_name(parent_id: str, child_id: str) -> str:
    """Get the branch name for a child.

    Args:
        parent_id: The parent ID.
        child_id: The child ID.

    Returns:
        The branch name (parent_id/child_id).
    """
    return f"{parent_id}/{child_id}"
