"""LintGate - Enforces code style and quality via ruff."""

import subprocess

from src.gates.quality_gate import GateResult


class LintGate:
    """Quality gate that runs ruff linting.

    Executes ruff check on the src/ directory and fails if any linting errors
    or warnings are found. Treats all warnings as failures (non-negotiable).
    """

    def check(self) -> GateResult:
        """Run ruff linter on source code.

        Returns:
            GateResult: Result indicating if linting passed
        """
        try:
            result = subprocess.run(
                ["ruff", "check", "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="Lint gate passed: No linting issues found",
                    details={
                        "return_code": result.returncode,
                        "stdout": result.stdout,
                        "stderr": result.stderr,
                    },
                )
            else:
                return GateResult(
                    passed=False,
                    message="Lint gate failed: Linting issues detected",
                    details={
                        "return_code": result.returncode,
                        "stdout": result.stdout,
                        "stderr": result.stderr,
                    },
                )

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

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

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