"""BuildGate - Enforces type checking via mypy."""

import subprocess

from src.gates.quality_gate import GateResult


class BuildGate:
    """Quality gate that runs mypy type checking.

    Executes mypy on the src/ directory and fails if any type errors are found.
    Uses strict mode configuration from pyproject.toml.
    """

    def check(self) -> GateResult:
        """Run mypy type checker on source code.

        Returns:
            GateResult: Result indicating if type checking passed
        """
        try:
            result = subprocess.run(
                ["mypy", "src/"],
                capture_output=True,
                text=True,
                check=False,  # Don't raise on non-zero exit
                timeout=300,  # 5 minute timeout
            )

            if result.returncode == 0:
                return GateResult(
                    passed=True,
                    message="Build gate passed: No type errors found",
                    details={
                        "return_code": result.returncode,
                        "stdout": result.stdout,
                        "stderr": result.stderr,
                    },
                )
            else:
                return GateResult(
                    passed=False,
                    message="Build gate failed: Type errors detected",
                    details={
                        "return_code": result.returncode,
                        "stdout": result.stdout,
                        "stderr": result.stderr,
                    },
                )

        except FileNotFoundError as e:
            return GateResult(
                passed=False,
                message="Build gate failed: mypy not found or not installed",
                details={"error": str(e)},
            )

        except subprocess.TimeoutExpired as e:
            return GateResult(
                passed=False,
                message=f"Build gate failed: mypy timed out after {e.timeout} seconds",
                details={"error": str(e), "timeout": e.timeout},
            )

        except Exception as e:
            return GateResult(
                passed=False,
                message=f"Build gate failed: Unexpected error: {e}",
                details={"error": str(e)},
            )
