import subprocess

import pytest

from project_brain.graph.json_store import JsonStore
from project_brain.graph.models import Edge
from project_brain.query.engine import QueryEngine
from project_brain.query.git_diff import GitBudgetExceeded, GitDiffReader
from project_brain.query.index import FileIndex, KeywordIndex, SymbolIndex


def _git(project, *args):
    return subprocess.run(
        ["git", *args],
        cwd=project,
        check=True,
        capture_output=True,
        text=True,
    ).stdout.strip()


def test_reads_bounded_commit_pairs_and_unified_diff(tmp_path):
    _git(tmp_path, "init")
    _git(tmp_path, "config", "user.email", "test@example.com")
    _git(tmp_path, "config", "user.name", "Test User")
    source = tmp_path / "service.py"
    source.write_text("def value():\n    return 1\n", encoding="utf-8")
    _git(tmp_path, "add", "service.py")
    _git(tmp_path, "commit", "-m", "initial")
    source.write_text("def value():\n    return 2\n", encoding="utf-8")
    _git(tmp_path, "commit", "-am", "update")
    sha = _git(tmp_path, "rev-parse", "HEAD")
    reader = GitDiffReader(tmp_path)

    changes = reader.changes(sha)
    before, after = reader.file_pair(sha, changes[0])

    assert reader.available()
    assert changes[0].path == "service.py"
    assert "return 1" in before
    assert "return 2" in after
    assert "-    return 1" in reader.unified(sha, changes[0])
    assert reader.latest_commit("service.py") == sha


def test_query_engine_resolves_file_symbol_and_commit_targets(tmp_path):
    _git(tmp_path, "init")
    _git(tmp_path, "config", "user.email", "test@example.com")
    _git(tmp_path, "config", "user.name", "Test User")
    source = tmp_path / "service.py"
    source.write_text("def value():\n    return 1\n", encoding="utf-8")
    _git(tmp_path, "add", "service.py")
    _git(tmp_path, "commit", "-m", "initial")
    source.write_text("def value():\n    return 2\n", encoding="utf-8")
    _git(tmp_path, "commit", "-am", "update")
    sha = _git(tmp_path, "rev-parse", "HEAD")

    store = JsonStore(tmp_path / ".brain")
    store.add_node({"id": "file_1", "type": "file", "path": "service.py"})
    store.add_node({
        "id": "fn_1",
        "type": "function",
        "name": "value",
        "path": "service.py",
        "line_start": 1,
        "line_end": 2,
    })
    store.add_node({"id": "commit_1", "type": "commit", "sha": sha})
    store.add_edge(Edge(id="contains", type="CONTAIN", source="file_1", target="fn_1"))
    symbols = SymbolIndex()
    symbols.add("value", "fn_1")
    files = FileIndex()
    files.add("service.py", {"file_id": "file_1", "nodes": ["fn_1"]})
    query = QueryEngine(
        store,
        KeywordIndex(),
        symbols,
        files,
        project_path=str(tmp_path),
    )

    file_result = query.get_change_diff("service.py")
    symbol_result = query.get_change_diff("value", format="pair")
    commit_result = query.get_change_diff("commit_1")

    assert file_result["commit_sha"] == sha
    assert file_result["changes"][0]["changed_functions"] == ["fn_1"]
    assert "-    return 1" in file_result["changes"][0]["diff"]
    assert "return 1" in symbol_result["changes"][0]["before"]
    assert "return 2" in symbol_result["changes"][0]["after"]
    assert commit_result["changes"][0]["file"] == "service.py"


def test_rejects_revision_option_injection(tmp_path):
    reader = GitDiffReader(tmp_path)

    with pytest.raises(RuntimeError, match="invalid Git commit id"):
        reader.changes("--output=outside")


def test_enforces_request_time_budget(tmp_path):
    with pytest.raises(GitBudgetExceeded, match="time budget"):
        GitDiffReader(tmp_path, max_response_seconds=0).changes("abcdef12")


def test_enforces_aggregate_output_budget(tmp_path):
    _git(tmp_path, "init")
    _git(tmp_path, "config", "user.email", "test@example.com")
    _git(tmp_path, "config", "user.name", "Test User")
    source = tmp_path / "large.py"
    source.write_text("value = 'before'\n", encoding="utf-8")
    _git(tmp_path, "add", "large.py")
    _git(tmp_path, "commit", "-m", "initial")
    source.write_text("value = '" + "after" * 100 + "'\n", encoding="utf-8")
    _git(tmp_path, "commit", "-am", "large update")
    sha = _git(tmp_path, "rev-parse", "HEAD")
    reader = GitDiffReader(tmp_path, max_response_bytes=256)

    assert reader.available()
    change = reader.changes(sha)[0]
    with pytest.raises(GitBudgetExceeded, match="byte budget"):
        reader.unified(sha, change)


def test_supports_project_root_inside_git_worktree(tmp_path):
    _git(tmp_path, "init")
    _git(tmp_path, "config", "user.email", "test@example.com")
    _git(tmp_path, "config", "user.name", "Test User")
    project = tmp_path / "packages" / "brain"
    project.mkdir(parents=True)
    source = project / "service.py"
    source.write_text("value = 1\n", encoding="utf-8")
    _git(tmp_path, "add", ".")
    _git(tmp_path, "commit", "-m", "initial")
    source.write_text("value = 2\n", encoding="utf-8")
    _git(tmp_path, "commit", "-am", "update nested project")
    sha = _git(tmp_path, "rev-parse", "HEAD")
    reader = GitDiffReader(project)

    assert reader.available()
    changes = reader.changes(sha)
    assert [change.path for change in changes] == ["service.py"]
    assert "value = 2" in reader.file_pair(sha, changes[0])[1]


def test_merge_commit_uses_first_parent_diff(tmp_path):
    _git(tmp_path, "init")
    _git(tmp_path, "config", "user.email", "test@example.com")
    _git(tmp_path, "config", "user.name", "Test User")
    source = tmp_path / "service.py"
    source.write_text("value = 1\n", encoding="utf-8")
    _git(tmp_path, "add", "service.py")
    _git(tmp_path, "commit", "-m", "initial")
    _git(tmp_path, "checkout", "-b", "feature")
    source.write_text("value = 2\n", encoding="utf-8")
    _git(tmp_path, "commit", "-am", "feature change")
    _git(tmp_path, "checkout", "master")
    (tmp_path / "other.txt").write_text("main\n", encoding="utf-8")
    _git(tmp_path, "add", "other.txt")
    _git(tmp_path, "commit", "-m", "main change")
    _git(tmp_path, "merge", "--no-ff", "feature", "-m", "merge feature")
    sha = _git(tmp_path, "rev-parse", "HEAD")
    reader = GitDiffReader(tmp_path)

    changes = reader.changes(sha)
    service_change = next(change for change in changes if change.path == "service.py")
    before, after = reader.file_pair(sha, service_change)
    assert "value = 1" in before
    assert "value = 2" in after
    assert "value = 2" in reader.unified(sha, service_change)