from __future__ import annotations

import re
import subprocess
import threading
import time
from dataclasses import dataclass
from pathlib import Path


MAX_DIFF_BYTES = 2 * 1024 * 1024
MAX_FILE_BYTES = 2 * 1024 * 1024
MAX_RESPONSE_BYTES = 2 * 1024 * 1024
MAX_CHANGED_FILES = 200
MAX_RESPONSE_SECONDS = 30.0


class GitBudgetExceeded(RuntimeError):
    """Raised when a bounded Git request exhausts its byte/time budget."""


class GitCommandError(RuntimeError):
    """Raised when Git rejects a request or the repository is unavailable."""


@dataclass(frozen=True)
class GitFileChange:
    status: str
    old_path: str | None
    new_path: str | None

    @property
    def path(self) -> str:
        return self.new_path or self.old_path or ""


class GitDiffReader:
    """Bounded, argument-safe access to commit/file content from local Git."""

    def __init__(
        self,
        project_path: str | Path,
        *,
        max_response_bytes: int = MAX_RESPONSE_BYTES,
        max_response_seconds: float = MAX_RESPONSE_SECONDS,
    ):
        self.project_path = Path(project_path)
        self._remaining_bytes = max(0, int(max_response_bytes))
        self._deadline = time.monotonic() + max(0.0, float(max_response_seconds))
        self._repository_checked = False
        self._repository_available = False
        self._repo_prefix = ""
        self._parent_cache: dict[str, str | None] = {}

    @property
    def remaining_bytes(self) -> int:
        return self._remaining_bytes

    def available(self) -> bool:
        try:
            self._ensure_repository()
        except (OSError, RuntimeError):
            return False
        return self._repository_available

    def latest_commit(self, path: str) -> str | None:
        self._ensure_repository()
        output = self._run_text(["log", "-1", "--format=%H", "--", path])
        value = output.strip()
        return value if value else None

    def latest_commit_for_lines(
        self, path: str, line_start: int, line_end: int
    ) -> str | None:
        """Return the latest commit touching a current line range."""
        self._ensure_repository()
        start = max(1, int(line_start))
        end = max(start, int(line_end))
        repo_path = self._repo_path(path)
        output = self._run_text(
            [
                "log",
                f"-L{start},{end}:{repo_path}",
                "-1",
                "--format=%H",
                "--no-patch",
            ],
            max_bytes=1024,
        )
        value = output.strip().splitlines()
        return value[0] if value else None

    def changes(self, sha: str) -> list[GitFileChange]:
        self._validate_revision(sha)
        self._ensure_repository()
        parent = self._first_parent(sha)
        if parent is not None:
            revisions = [parent, sha]
            root_flag: list[str] = []
        else:
            revisions = [sha]
            root_flag = ["--root"]
        raw = self._run_bytes(
            [
                "diff-tree", *root_flag, "--no-commit-id", "--name-status",
                "--find-renames", "-r", "-z", *revisions,
            ],
            max_bytes=MAX_DIFF_BYTES,
        )
        fields = raw.decode("utf-8", errors="replace").split("\0")
        changes: list[GitFileChange] = []
        index = 0
        while index < len(fields) and len(changes) < MAX_CHANGED_FILES:
            status = fields[index]
            index += 1
            if not status:
                continue
            code = status[:1]
            if code in {"R", "C"}:
                if index + 1 >= len(fields):
                    break
                old_path, new_path = fields[index], fields[index + 1]
                index += 2
            else:
                if index >= len(fields):
                    break
                path = fields[index]
                index += 1
                old_path = None if code == "A" else path
                new_path = None if code == "D" else path
            old_path = self._local_path(old_path)
            new_path = self._local_path(new_path)
            if old_path is None and new_path is None:
                continue
            if code in {"R", "C"}:
                if old_path is None:
                    code = "A"
                elif new_path is None:
                    code = "D"
            changes.append(GitFileChange(code, old_path, new_path))
        return changes

    def file_pair(self, sha: str, change: GitFileChange) -> tuple[str | None, str | None]:
        self._validate_revision(sha)
        self._ensure_repository()
        parent = self._first_parent(sha)
        before = self._show_file(parent, change.old_path) if parent and change.old_path else None
        after = self._show_file(sha, change.new_path) if change.new_path else None
        return before, after

    def unified(self, sha: str, change: GitFileChange) -> str:
        self._validate_revision(sha)
        self._ensure_repository()
        paths = [path for path in (change.old_path, change.new_path) if path]
        parent = self._first_parent(sha)
        if parent is None:
            args = [
                "show", "--format=", "--no-ext-diff", "--find-renames",
                "--unified=3", sha, "--", *dict.fromkeys(paths),
            ]
        else:
            args = [
                "diff", "--no-ext-diff", "--find-renames", "--unified=3",
                parent, sha, "--", *dict.fromkeys(paths),
            ]
        return self._run_text(args, max_bytes=MAX_DIFF_BYTES)

    def _show_file(self, revision: str, path: str | None) -> str | None:
        if not path:
            return None
        try:
            raw = self._run_bytes(
                ["show", f"{revision}:{self._repo_path(path)}"],
                max_bytes=MAX_FILE_BYTES,
            )
        except (OSError, GitCommandError):
            return None
        return raw.decode("utf-8", errors="replace")

    def _run_text(self, args: list[str], *, max_bytes: int = MAX_DIFF_BYTES) -> str:
        return self._run_bytes(args, max_bytes=max_bytes).decode(
            "utf-8", errors="replace",
        )

    def _run_bytes(self, args: list[str], *, max_bytes: int) -> bytes:
        allowed = min(max(0, int(max_bytes)), self._remaining_bytes)
        seconds_left = self._deadline - time.monotonic()
        if allowed <= 0:
            raise GitBudgetExceeded("Git diff response byte budget exhausted")
        if seconds_left <= 0:
            raise GitBudgetExceeded("Git diff time budget exhausted")

        try:
            process = subprocess.Popen(
                ["git", *args],
                cwd=str(self.project_path),
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
        except OSError as exc:
            raise GitCommandError(str(exc)) from exc

        output = bytearray()
        error = bytearray()
        overflow = threading.Event()

        def read_stdout() -> None:
            assert process.stdout is not None
            while True:
                chunk = process.stdout.read(64 * 1024)
                if not chunk:
                    return
                capacity = allowed + 1 - len(output)
                if capacity > 0:
                    output.extend(chunk[:capacity])
                if len(output) > allowed or len(chunk) > max(0, capacity):
                    overflow.set()
                    try:
                        process.terminate()
                    except OSError:
                        pass
                    return

        def read_stderr() -> None:
            assert process.stderr is not None
            while True:
                chunk = process.stderr.read(16 * 1024)
                if not chunk:
                    return
                capacity = 64 * 1024 - len(error)
                if capacity > 0:
                    error.extend(chunk[:capacity])

        stdout_thread = threading.Thread(target=read_stdout, daemon=True)
        stderr_thread = threading.Thread(target=read_stderr, daemon=True)
        stdout_thread.start()
        stderr_thread.start()
        timed_out = False
        try:
            process.wait(timeout=min(30.0, seconds_left))
        except subprocess.TimeoutExpired:
            timed_out = True
            try:
                process.kill()
            finally:
                process.wait()
        finally:
            stdout_thread.join(timeout=2.0)
            stderr_thread.join(timeout=2.0)
            if process.stdout is not None:
                process.stdout.close()
            if process.stderr is not None:
                process.stderr.close()

        if timed_out:
            raise GitBudgetExceeded("Git diff time budget exhausted")
        if overflow.is_set() or len(output) > allowed:
            self._remaining_bytes = 0
            raise GitBudgetExceeded("Git diff response byte budget exhausted")
        if process.returncode != 0:
            message = bytes(error).decode("utf-8", errors="replace").strip()
            raise GitCommandError(message or f"git {' '.join(args[:2])} failed")
        self._remaining_bytes -= len(output)
        return bytes(output)

    def _ensure_repository(self) -> None:
        if self._repository_checked:
            if not self._repository_available:
                raise GitCommandError("not inside a Git work tree")
            return
        self._repository_checked = True
        try:
            inside = self._run_text(
                ["rev-parse", "--is-inside-work-tree"], max_bytes=64,
            ).strip()
            if inside != "true":
                raise GitCommandError("not inside a Git work tree")
            self._repo_prefix = self._run_text(
                ["rev-parse", "--show-prefix"], max_bytes=4096,
            ).strip().replace("\\", "/")
        except (OSError, RuntimeError):
            self._repository_available = False
            raise
        self._repository_available = True

    def _first_parent(self, revision: str) -> str | None:
        self._validate_revision(revision)
        if revision in self._parent_cache:
            return self._parent_cache[revision]
        fields = self._run_text(
            ["rev-list", "--parents", "-n", "1", revision], max_bytes=1024,
        ).strip().split()
        if not fields:
            raise GitCommandError(f"unknown Git commit: {revision}")
        parent = fields[1] if len(fields) > 1 else None
        self._parent_cache[revision] = parent
        return parent

    def _repo_path(self, path: str) -> str:
        path = str(path).replace("\\", "/")
        while path.startswith("./"):
            path = path[2:]
        return f"{self._repo_prefix}{path}" if self._repo_prefix else path

    def _local_path(self, path: str | None) -> str | None:
        if path is None:
            return None
        path = path.replace("\\", "/")
        if not self._repo_prefix:
            return path
        if not path.startswith(self._repo_prefix):
            return None
        return path[len(self._repo_prefix):]

    @staticmethod
    def _validate_revision(revision: str) -> None:
        # Only object IDs are accepted.  This keeps graph metadata from being
        # interpreted as additional Git options or revision expressions.
        if not re.fullmatch(r"[0-9a-fA-F]{4,64}", revision):
            raise GitCommandError("invalid Git commit id")