import importlib
import subprocess
from pathlib import Path

import pytest


git_tools = importlib.import_module("gjalla_precommit.tools.git_tools")


def _run_git(repo_path: Path, *args: str) -> str:
    result = subprocess.run(
        ["git", *args],
        cwd=repo_path,
        check=True,
        capture_output=True,
        text=True,
    )
    return result.stdout.strip()


def test_get_staged_diff(staged_repo: Path):
    diff = git_tools.get_staged_diff(staged_repo)
    assert "src/auth/login.py" in diff


def test_get_staged_diff_empty(temp_repo: Path):
    diff = git_tools.get_staged_diff(temp_repo)
    assert diff == ""


def test_get_branch_name(temp_repo: Path):
    branch = git_tools.get_branch_name(temp_repo)
    assert branch in {"main", "master"}


def test_get_branch_name_detached(detached_repo: Path):
    branch = git_tools.get_branch_name(detached_repo)
    assert len(branch) >= 7


def test_attach_receipt_via_notes(temp_repo: Path, sample_receipt: dict):
    git_tools.attach_receipt_via_notes(temp_repo, sample_receipt)
    note = _run_git(temp_repo, "notes", "--ref", git_tools.NOTES_REF, "show", "HEAD")
    assert sample_receipt["receipt_id"] in note


def test_attach_receipt_via_trailer(temp_repo: Path, sample_receipt: dict):
    git_tools.attach_receipt_via_trailer(temp_repo, sample_receipt["receipt_id"])
    message = _run_git(temp_repo, "log", "-1", "--pretty=%B")
    assert f"Gjalla-Receipt: {sample_receipt['receipt_id']}" in message


def test_notes_ref_uses_gjalla_namespace():
    assert git_tools.NOTES_REF == "refs/notes/gjalla"


def test_get_commit_message(temp_repo: Path):
    message = git_tools.get_commit_message(temp_repo)
    assert message == "Initial commit"


def test_extract_ticket_references():
    refs = git_tools.extract_ticket_references("Closes LINEAR-123, fixes #456")
    assert "LINEAR-123" in refs
    assert "#456" in refs


def test_not_in_git_repo_error(tmp_path: Path):
    with pytest.raises(git_tools.GitToolError):
        git_tools.get_staged_diff(tmp_path)


def test_receipt_attached_after_analysis(temp_repo: Path, sample_receipt: dict):
    file_path = temp_repo / "flow.py"
    file_path.write_text("print('flow')\n", encoding="utf-8")
    _run_git(temp_repo, "add", "flow.py")
    _run_git(temp_repo, "commit", "-m", "Flow commit")

    git_tools.attach_receipt_via_notes(temp_repo, sample_receipt)

    note = _run_git(temp_repo, "notes", "--ref", git_tools.NOTES_REF, "show", "HEAD")
    assert sample_receipt["receipt_id"] in note
