#!/usr/bin/env python3
"""Run the default pytest suite on one Python version in a temporary venv."""

from __future__ import annotations

import os
import subprocess
import sys
import tempfile
from pathlib import Path


def run(version: str, pytest_args: list[str]) -> int:
    root = Path(__file__).resolve().parents[1]
    with tempfile.TemporaryDirectory(prefix=f"pygitweb-{version}-", ignore_cleanup_errors=True) as tmp:
        env = os.environ.copy()
        env.pop("VIRTUAL_ENV", None)
        env.pop("PYTHONHOME", None)
        env["UV_PROJECT_ENVIRONMENT"] = str(Path(tmp) / ".venv")
        sync = subprocess.run(
            ["uv", "sync", "--all-packages", "--python", version],
            cwd=root,
            env=env,
            check=False,
        )
        if sync.returncode != 0:
            return sync.returncode
        proc = subprocess.run(
            ["uv", "run", "--python", version, "pytest", ".", *pytest_args],
            cwd=root,
            env=env,
            check=False,
        )
        return proc.returncode


def main() -> int:
    if len(sys.argv) < 2 or sys.argv[1] == "":
        print("usage: pytest_version.py VERSION [pytest args...]", file=sys.stderr)
        return 2
    return run(sys.argv[1], sys.argv[2:])


if __name__ == "__main__":
    raise SystemExit(main())