"""Git worktree operations for orchestrate workers."""

from __future__ import annotations

import subprocess
from pathlib import Path


class WorktreeError(RuntimeError):
    """Raised when a git worktree operation fails."""


def _git(args: list[str], cwd: Path) -> str:
    result = subprocess.run(
        ["git", *args],
        cwd=str(cwd),
        capture_output=True,
        text=True,
    )
    if result.returncode != 0:
        raise WorktreeError(
            f"git {' '.join(args)} failed in {cwd}:\n{result.stderr.strip()}"
        )
    return result.stdout.strip()


def worktree_branch_name(task_id: str, run_id: str) -> str:
    """Return the git branch name for a task worktree."""
    return f"orchestrate/{task_id.lower()}-{run_id}"


def create_worktree(repo: Path, worktree_path: Path, branch: str) -> None:
    """Create a new git worktree at worktree_path on a new branch."""
    worktree_path.parent.mkdir(parents=True, exist_ok=True)
    _git(["worktree", "add", "-b", branch, str(worktree_path)], cwd=repo)


def reset_worktree(worktree_path: Path) -> None:
    """Reset worktree to HEAD: discard tracked changes and untracked files."""
    _git(["checkout", "."], cwd=worktree_path)
    _git(["clean", "-fd"], cwd=worktree_path)


def delete_worktree(repo: Path, worktree_path: Path, branch: str) -> None:
    """Remove a worktree and delete its branch."""
    try:
        _git(["worktree", "remove", "--force", str(worktree_path)], cwd=repo)
    except WorktreeError:
        pass  # already gone

    try:
        _git(["branch", "-D", branch], cwd=repo)
    except WorktreeError:
        pass  # branch already deleted
