#!/usr/bin/env python3
"""Stand-in for nvcc used to exercise compile_assets.py / seal_pins.py on machines without CUDA.

It writes a minimal, obviously fake PTX (marker 'FAKE-NVCC') with the entries named in
FAKE_NVCC_ENTRIES ("name[:param_count],...") and FAKE_NVCC_PREFIX ("prefix:count,...").  Nothing here is a
compiler: never seal its output into a real tree.
"""
import hashlib
import os
import sys


def main(argv):
    if "--version" in argv or "-V" in argv:
        print("nvcc: NVIDIA (R) Cuda compiler driver (FAKE fake-nvcc, not a compiler)")
        print("Cuda compilation tools, release 13.0, V13.2.86")
        return 0
    out = None
    source = None
    i = 0
    while i < len(argv):
        a = argv[i]
        if a == "-o" and i + 1 < len(argv):
            out = argv[i + 1]
            i += 2
            continue
        if a.endswith(".cu"):
            source = a
        i += 1
    if out is None or source is None:
        print("fake-nvcc: need a .cu input and -o OUTPUT", file=sys.stderr)
        return 1
    if not os.path.isfile(source):
        print(f"fake-nvcc: cannot open {source}", file=sys.stderr)
        return 1
    if os.environ.get("FAKE_NVCC_FAIL") and os.environ["FAKE_NVCC_FAIL"] in source:
        print("fake-nvcc: requested failure", file=sys.stderr)
        return 2
    with open(source, "rb") as f:
        digest = hashlib.sha256(f.read()).hexdigest()
    flags_digest = hashlib.sha256(" ".join(argv).encode()).hexdigest()
    lines = [
        "// FAKE-NVCC: not compiler output; pipeline test only",
        f"// source sha256 {digest}",
        f"// argv sha256 {flags_digest}",
        ".version 8.7",
        ".target sm_120",
        ".address_size 64",
        "",
    ]
    entries = []
    for item in filter(None, os.environ.get("FAKE_NVCC_ENTRIES", "").split(",")):
        name, _, n = item.partition(":")
        entries.append((name, int(n) if n else 1))
    for item in filter(None, os.environ.get("FAKE_NVCC_PREFIX", "").split(",")):
        prefix, _, n = item.rpartition(":")
        entries += [(f"{prefix}_fake{k}", 1) for k in range(int(n))]
    for name, nparams in entries:
        params = ",\n".join(f"\t.param .u64 {name}_param_{k}" for k in range(nparams))
        lines += [f".visible .entry {name}(", params, ")", "{", "\tret;", "}", ""]
    with open(out, "w", encoding="ascii", newline="\n") as f:
        f.write("\n".join(lines))
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
