# src/onako/worktree_manager.py
import subprocess
from pathlib import Path


class WorktreeManager:
    def __init__(self, repo_path: Path | str):
        self.repo_path = Path(repo_path).resolve()

    def _worktree_path(self, branch: str) -> Path:
        """Sibling directory with double-dash separator."""
        safe_branch = branch.replace("/", "--")
        return self.repo_path.parent / f"{self.repo_path.name}--{safe_branch}"

    def ensure_worktree(self, branch: str, base: str = "main") -> Path:
        """Ensure worktree exists for branch, creating if needed. Returns path."""
        wt_path = self._worktree_path(branch)

        # Check if worktree already exists
        if wt_path.exists():
            return wt_path

        # Check if branch exists
        result = subprocess.run(
            ["git", "branch", "--list", branch],
            cwd=self.repo_path, capture_output=True, text=True
        )
        branch_exists = branch in result.stdout

        if branch_exists:
            # Add worktree for existing branch
            subprocess.run(
                ["git", "worktree", "add", str(wt_path), branch],
                cwd=self.repo_path, check=True, capture_output=True
            )
        else:
            # Create new branch and worktree
            subprocess.run(
                ["git", "worktree", "add", "-b", branch, str(wt_path), base],
                cwd=self.repo_path, check=True, capture_output=True
            )

        return wt_path

    def list_worktrees(self) -> list[dict]:
        """List all worktrees with branch and path info."""
        result = subprocess.run(
            ["git", "worktree", "list", "--porcelain"],
            cwd=self.repo_path, capture_output=True, text=True, check=True
        )

        worktrees = []
        current = {}
        for line in result.stdout.strip().split("\n"):
            if line.startswith("worktree "):
                if current and current.get("branch"):
                    worktrees.append(current)
                current = {"path": Path(line[9:])}
            elif line.startswith("branch refs/heads/"):
                current["branch"] = line[18:]

        if current and current.get("branch"):
            worktrees.append(current)

        # Exclude main repo (it's a worktree too but not one we created)
        worktrees = [wt for wt in worktrees if wt["path"] != self.repo_path]

        return worktrees

    def delete_worktree(self, branch: str) -> None:
        """Remove worktree for the given branch."""
        wt_path = self._worktree_path(branch)

        subprocess.run(
            ["git", "worktree", "remove", "--force", str(wt_path)],
            cwd=self.repo_path, check=True, capture_output=True
        )
