# tests/test_worktree_manager.py
import subprocess
from pathlib import Path
import pytest
from onako.worktree_manager import WorktreeManager


@pytest.fixture
def git_repo(tmp_path):
    """Create a test git repo with initial commit."""
    repo = tmp_path / "repo"
    repo.mkdir()
    subprocess.run(["git", "init"], cwd=repo, check=True, capture_output=True)
    subprocess.run(["git", "config", "user.email", "test@test.com"], cwd=repo, check=True, capture_output=True)
    subprocess.run(["git", "config", "user.name", "Test"], cwd=repo, check=True, capture_output=True)
    (repo / "README.md").write_text("# Test")
    subprocess.run(["git", "add", "."], cwd=repo, check=True, capture_output=True)
    subprocess.run(["git", "commit", "-m", "initial"], cwd=repo, check=True, capture_output=True)
    yield repo
    # Cleanup worktrees
    subprocess.run(["git", "worktree", "prune"], cwd=repo, capture_output=True)


@pytest.fixture
def manager(git_repo):
    return WorktreeManager(repo_path=git_repo)


def test_ensure_worktree_creates_branch_and_worktree(manager, git_repo):
    path = manager.ensure_worktree("feature-x")

    # Worktree path is sibling with double-dash separator
    expected = git_repo.parent / f"{git_repo.name}--feature-x"
    assert path == expected
    assert expected.exists()

    # Branch was created
    result = subprocess.run(
        ["git", "branch", "--list", "feature-x"],
        cwd=git_repo, capture_output=True, text=True
    )
    assert "feature-x" in result.stdout


def test_ensure_worktree_reuses_existing(manager, git_repo):
    path1 = manager.ensure_worktree("feature-y")
    path2 = manager.ensure_worktree("feature-y")
    assert path1 == path2


def test_list_worktrees(manager, git_repo):
    manager.ensure_worktree("branch-a")
    manager.ensure_worktree("branch-b")

    worktrees = manager.list_worktrees()

    assert len(worktrees) == 2
    branches = [wt["branch"] for wt in worktrees]
    assert "branch-a" in branches
    assert "branch-b" in branches
    assert all("path" in wt for wt in worktrees)


def test_delete_worktree(manager, git_repo):
    path = manager.ensure_worktree("to-delete")
    assert path.exists()

    manager.delete_worktree("to-delete")

    assert not path.exists()
    worktrees = manager.list_worktrees()
    assert not any(wt["branch"] == "to-delete" for wt in worktrees)
