"""Shared fixtures for pgt TUI tests."""

from __future__ import annotations

import gc
from collections.abc import Iterator
from pathlib import Path
from unittest.mock import MagicMock

import pytest
from pygit2 import Repository, Signature, init_repository
from pyratatui import Rect

from pygittools.tui.types import PageContext

SIG = Signature("tester", "tester@example.com", 0)


@pytest.fixture(autouse=True)
def _drop_unsendable_prompt_state() -> Iterator[None]:
    # TextState is unsendable. Drop it on this thread once the test and its
    # fixtures have released the page, before another thread's GC can.
    yield
    gc.collect()


@pytest.fixture(autouse=True)
def _mock_worktree_list(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(
        "pygittools.tui.worktrees_list.list_worktrees",
        lambda _repo: ([], None),
    )


@pytest.fixture
def repo(tmp_path: Path) -> Repository:
    repo_path = tmp_path / "repo"
    repo_path.mkdir()
    return init_repository(str(repo_path), bare=False)


@pytest.fixture
def page_ctx(repo: Repository) -> PageContext:
    return PageContext(repo=repo, repo_path=Path(repo.path))


@pytest.fixture
def committed_repo(repo: Repository) -> Repository:
    workdir = Path(repo.workdir)
    (workdir / "tracked.txt").write_text("v1\n", encoding="utf-8")
    repo.index.add("tracked.txt")
    repo.index.write()
    tree = repo.index.write_tree()
    repo.create_commit("HEAD", SIG, SIG, "initial", tree, [])
    return repo


@pytest.fixture
def frame() -> MagicMock:
    return MagicMock()


@pytest.fixture
def area() -> Rect:
    return Rect(0, 0, 80, 24)