"""Shared fixtures for gwtm tests."""

from __future__ import annotations

import os
import subprocess
from pathlib import Path

import pytest


@pytest.fixture
def temp_git_repo(tmp_path: Path) -> Path:
    """Create a temporary git repo with an initial commit."""
    repo = tmp_path / "test-repo"
    repo.mkdir()

    subprocess.run(["git", "init"], cwd=repo, capture_output=True, check=True)
    subprocess.run(["git", "config", "user.email", "test@test.com"], cwd=repo, capture_output=True, check=True)
    subprocess.run(["git", "config", "user.name", "Test"], cwd=repo, capture_output=True, check=True)

    # Create initial commit
    (repo / "README.md").write_text("# Test Repo\n")
    subprocess.run(["git", "add", "."], cwd=repo, capture_output=True, check=True)
    subprocess.run(["git", "commit", "-m", "Initial commit"], cwd=repo, capture_output=True, check=True)

    return repo


@pytest.fixture
def temp_git_repo_with_remote(tmp_path: Path) -> tuple[Path, Path]:
    """Create a temp repo with a local bare remote.

    Returns (repo_path, remote_path).
    """
    # Create bare remote
    remote = tmp_path / "remote.git"
    remote.mkdir()
    subprocess.run(["git", "init", "--bare"], cwd=remote, capture_output=True, check=True)

    # Clone it to get a working repo
    repo = tmp_path / "test-repo"
    subprocess.run(
        ["git", "clone", str(remote), str(repo)],
        capture_output=True, check=True,
    )
    subprocess.run(["git", "config", "user.email", "test@test.com"], cwd=repo, capture_output=True, check=True)
    subprocess.run(["git", "config", "user.name", "Test"], cwd=repo, capture_output=True, check=True)

    # Create initial commit and push
    (repo / "README.md").write_text("# Test Repo\n")
    subprocess.run(["git", "add", "."], cwd=repo, capture_output=True, check=True)
    subprocess.run(["git", "commit", "-m", "Initial commit"], cwd=repo, capture_output=True, check=True)
    subprocess.run(["git", "push", "-u", "origin", "master"], cwd=repo, capture_output=True)
    # Try main too in case default is main
    subprocess.run(["git", "push", "-u", "origin", "HEAD"], cwd=repo, capture_output=True)

    return repo, remote


@pytest.fixture
def gwt_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
    """Set up a temporary config directory with monkeypatched paths."""
    import yaml

    config_dir = tmp_path / "config" / "gwtm"
    config_dir.mkdir(parents=True)

    worktrees_dir = tmp_path / "worktrees"
    worktrees_dir.mkdir()

    # Write a config file pointing to the temp worktrees dir
    config_file = config_dir / "config.yaml"
    config_file.write_text(yaml.dump({
        "worktrees_base": str(worktrees_dir),
        "branch_prefix": "wt/",
        "default_base_branch": "main",
        "sync_strategy": "rebase",
        "auto_fetch": True,
    }))

    # Monkeypatch the module-level paths
    import gwtm.config as config_mod
    monkeypatch.setattr(config_mod, "GLOBAL_CONFIG_DIR", config_dir)
    monkeypatch.setattr(config_mod, "GLOBAL_CONFIG_FILE", config_file)
    monkeypatch.setattr(config_mod, "WORKTREES_BASE", worktrees_dir)

    return config_dir


@pytest.fixture
def managed_repo(temp_git_repo: Path, gwt_config: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
    """A temp git repo with gwtm config pointing to tmp_path for worktrees."""
    import gwtm.config as config_mod

    wt_base = tmp_path / "worktrees"
    wt_base.mkdir(exist_ok=True)
    monkeypatch.setattr(config_mod, "WORKTREES_BASE", wt_base)

    return temp_git_repo
