"""TestGate - Enforces 100% test pass rate via pytest."""

import subprocess

from src.gates.quality_gate import GateResult


class TestGate:
    """Quality gate that runs pytest tests.

    Executes pytest and requires 100% pass rate (non-negotiable).
    Runs tests without coverage - coverage is handled by CoverageGate separately.
    """

    def check(self) -> GateResult:
        """Run pytest test suite.

        Returns:
            GateResult: Result indicating if all tests passed
        """
        try:
            result = subprocess.run(
                ["python", "-m", "pytest", "--no-cov", "-v"],
                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="Test gate passed: All tests passed (100% pass rate)",
                    details={
                        "return_code": result.returncode,
                        "stdout": result.stdout,
                        "stderr": result.stderr,
                    },
                )
            else:
                return GateResult(
                    passed=False,
                    message="Test gate failed: Test failures detected (requires 100% pass rate)",
                    details={
                        "return_code": result.returncode,
                        "stdout": result.stdout,
                        "stderr": result.stderr,
                    },
                )

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

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

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