"""Allowlisted command runner. Only pytest is permitted."""

from __future__ import annotations

import subprocess
import pathlib
from dataclasses import dataclass

ALLOWLIST = {"pytest"}


@dataclass
class ExecResult:
    command: str
    returncode: int
    stdout: str
    stderr: str
    blocked: bool = False


def run_command(
    cmd: str,
    args: list[str] | None = None,
    cwd: pathlib.Path | None = None,
    apply_mode: bool = False,
) -> ExecResult:
    """Run an allowlisted command. Refuse anything not in ALLOWLIST.
    Also refuse if apply_mode is False (dry-run blocks execution)."""
    if cmd not in ALLOWLIST:
        return ExecResult(
            command=cmd,
            returncode=-1,
            stdout="",
            stderr=f"Command '{cmd}' is not in the allowlist: {ALLOWLIST}",
            blocked=True,
        )
    if not apply_mode:
        return ExecResult(
            command=cmd,
            returncode=-1,
            stdout="",
            stderr="Execution blocked: --apply mode is not active.",
            blocked=True,
        )

    full_args = [cmd] + (args or [])
    try:
        result = subprocess.run(
            full_args,
            cwd=str(cwd) if cwd else None,
            capture_output=True,
            text=True,
            timeout=120,
        )
        return ExecResult(
            command=cmd,
            returncode=result.returncode,
            stdout=result.stdout,
            stderr=result.stderr,
        )
    except (FileNotFoundError, subprocess.TimeoutExpired) as exc:
        return ExecResult(
            command=cmd,
            returncode=-1,
            stdout="",
            stderr=str(exc),
        )
