import subprocess
import sys
import shutil


def run_tests(output_file: str = "test_durations.log", tests_dir: str = "tests", python_executable: str = None, use_uv: bool = True):
    """Run tests and log their durations."""
    
    # Prefer using uv run pytest if uv is available
    if use_uv and shutil.which("uv"):
        command = [
            "uv",
            "run",
            "pytest",
            tests_dir + "/",
            "--durations=0",
            "--durations-min=0",
            "--tb=short",
            "--disable-warnings",
            "-q",
            "-m",
            "not slow",
        ]
    else:
        # Fallback to python -m pytest
        if python_executable:
            if not python_executable.startswith("python"):
                python_cmd = f"python{python_executable}" if python_executable[0].isdigit() else python_executable
            else:
                python_cmd = python_executable
        else:
            python_cmd = sys.executable
        
        command = [
            python_cmd,
            "-m",
            "pytest",
            tests_dir + "/",
            "--durations=0",
            "--durations-min=0",
            "--tb=short",
            "--disable-warnings",
            "-q",
            "-m",
            "not slow",
        ]
    
    with open(output_file, "w") as f:
        result = subprocess.run(command, stdout=f)
        # Exit codes: 0 = all tests passed, 1 = tests failed or some were deselected, 5 = no tests collected
        # We only want to raise an error if tests actually failed (exit code > 1 or specific failure patterns)
        if result.returncode > 1:
            raise subprocess.CalledProcessError(result.returncode, command)

