#!/usr/bin/env python3
"""Read-only CUDA header/compiler path probe. Does not compile, install or delete.
--self-test checks synthetic test cases without touching GPUs.
"""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import shutil
import site
import sys


def categorize(header: bool, nvcc: bool) -> str:
    if header and nvcc:
        return "HEADER_AND_NVCC_DISCOVERED_NOT_COMPILE_TESTED"
    if header:
        return "HEADER_FOUND_NVCC_NOT_FOUND"
    if nvcc:
        return "NVCC_FOUND_HEADER_MISSING_FROM_SEARCH_LOCATIONS"
    return "NO_CUDA_HEADER_OR_NVCC_IN_COMMON_PATHS"


def test_cases() -> dict[str, object]:
    cases = [
        (True, True, "HEADER_AND_NVCC_DISCOVERED_NOT_COMPILE_TESTED"),
        (True, False, "HEADER_FOUND_NVCC_NOT_FOUND"),
        (False, True, "NVCC_FOUND_HEADER_MISSING_FROM_SEARCH_LOCATIONS"),
        (False, False, "NO_CUDA_HEADER_OR_NVCC_IN_COMMON_PATHS"),
    ]
    for h, n, expected in cases:
        assert categorize(h, n) == expected
    return {"status": "PASS", "synthetic_cases": len(cases), "commands_run": 0,
            "gpu_workloads": 0, "network_requests": 0}


def probe() -> dict[str, object]:
    candidates = []
    for root in [os.environ.get("CUDA_HOME"), os.environ.get("CUDA_PATH"),
                 "/usr/local/cuda", "/usr/local/cuda-12", "/usr/local/cuda-13"]:
        if root:
            base = Path(root).expanduser()
            candidates.extend([base / "include/cuda.h",
                               base / "targets/x86_64-linux/include/cuda.h",
                               base / "targets/aarch64-linux/include/cuda.h"])
    for root in [sys.prefix, *site.getsitepackages()]:
        base = Path(root)
        candidates.extend([base / "nvidia/cuda_runtime/include/cuda.h",
                           base / "nvidia/cuda_nvcc/include/cuda.h",
                           base / "nvidia/cuda_nvcc/targets/x86_64-linux/include/cuda.h"])
    seen = sorted({str(x) for x in candidates})
    present = [s for s in seen if Path(s).is_file()]
    nvcc = shutil.which("nvcc")
    return {
        "status": categorize(bool(present), nvcc is not None),
        "cuda_header_paths_found": present,
        "nvcc_in_path": bool(nvcc),
        "nvcc_path": nvcc,
        "tested_compilation": False,
        "tested_kernel": False,
        "warning": "This checks only common known paths and cannot prove headers are unavailable elsewhere.",
        "executed_commands": 0,
        "files_changed": 0,
    }


def main() -> int:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--self-test", action="store_true")
    args = p.parse_args()
    print(json.dumps(test_cases() if args.self_test else probe(), indent=2))
    return 0


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