#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
# 假的 nvidia-smi（測試用）：輸出格式照 NVIDIA 官方文件的 CSV、-q -x XML 與預設表格。
# POMELO_FAKE_SMI 選情境：ok（預設）、old（舊驅動：少幾個欄位）、nocomm（無法通訊）、noperm（值是 [Insufficient Permissions]）、
#   hang（不回應）、die（跑幾行就被中止）、na（部分欄位 [N/A]／[Not Supported]）、two（兩張卡）
import os, sys, time, math, re
sc = os.environ.get("POMELO_FAKE_SMI", "ok")
args = sys.argv[1:]
DRV = os.environ.get("POMELO_FAKE_DRV", "535.54.03")
if sc == "nocomm":
    print("NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.\n")
    sys.exit(9)
if sc == "hang":
    time.sleep(600)
OLD = {"clocks_event_reasons.active", "encoder.stats.sessionCount", "mig.mode.current", "clocks.max.mem"} if sc == "old" else set()
ALIAS_NEW = {"clocks_event_reasons.active"}
def gpus():
    n = 2 if sc in ("two", "na") else 1
    t = time.time()
    g = []
    for i in range(n):
        u = int(55 + 30 * math.sin(t / 3 + i))
        g.append(dict(index=i, name=["NVIDIA GeForce RTX 3090", "NVIDIA RTX A4000"][i], uuid="GPU-1234abcd-0000-0000-0000-00000000%04d" % i,
            **{"pci.bus_id": "00000000:%02X:00.0" % (1 + 2 * i), "driver_version": DRV, "memory.total": [24576, 16376][i], "memory.used": [11500, 15900][i], "memory.free": [13076, 476][i],
               "utilization.gpu": u, "utilization.memory": int(u * .6), "temperature.gpu": 64 + 12 * i, "fan.speed": 50, "power.draw": "%.2f" % (220 + 30 * i), "power.limit": "350.00",
               "clocks.gr": 1800, "clocks.sm": 1800, "clocks.mem": 9501, "clocks.max.gr": 2100, "clocks.max.mem": 9751, "pstate": "P2",
               "pcie.link.gen.current": 4, "pcie.link.width.current": 16, "pcie.link.gen.max": 4, "pcie.link.width.max": 16, "compute_cap": "8.6",
               "vbios_version": "94.02.42.00.A1", "ecc.mode.current": "[N/A]", "ecc.errors.uncorrected.volatile.total": "[N/A]", "ecc.errors.corrected.volatile.total": "[N/A]",
               "clocks_event_reasons.active": "0x0000000000000000", "clocks_throttle_reasons.active": "0x0000000000000000", "mig.mode.current": "[N/A]", "encoder.stats.sessionCount": 0}))
    if sc == "na":
        g[0]["fan.speed"] = "[Not Supported]"; g[0]["power.limit"] = "[N/A]"
    if sc == "noperm":
        for k in ("power.draw", "power.limit", "clocks.max.gr"): g[0][k] = "[Insufficient Permissions]"
    return g
if "--help-query-gpu" in args:
    allf = ["index", "name", "uuid", "pci.bus_id", "driver_version", "memory.total", "memory.used", "memory.free", "utilization.gpu", "utilization.memory", "temperature.gpu", "fan.speed",
            "power.draw", "power.limit", "clocks.gr", "clocks.sm", "clocks.mem", "clocks.max.gr", "clocks.max.mem", "pstate", "pcie.link.gen.current", "pcie.link.width.current",
            "pcie.link.gen.max", "pcie.link.width.max", "compute_cap", "vbios_version", "ecc.mode.current", "ecc.errors.uncorrected.volatile.total", "ecc.errors.corrected.volatile.total",
            "clocks_event_reasons.active", "clocks_throttle_reasons.active", "mig.mode.current", "encoder.stats.sessionCount", "count", "timestamp"]
    if sc == "old": allf = [f for f in allf if f not in OLD and f != "clocks_event_reasons.active"]
    else: allf = [f for f in allf if f != "clocks_event_reasons.active" or DRV >= "550"]
    print("List of valid properties to query for the switch \"--query-gpu=\":\n")
    for f in allf: print('"%s"\n    description of %s\n' % (f, f))
    sys.exit(0)
q = [a for a in args if a.startswith("--query-gpu=")]
if q:
    fields = q[0].split("=", 1)[1].split(",")
    valid = set(["index", "name", "uuid", "pci.bus_id", "driver_version", "memory.total", "memory.used", "memory.free", "utilization.gpu", "utilization.memory", "temperature.gpu", "fan.speed", "power.draw", "power.limit", "clocks.gr", "clocks.sm", "clocks.mem", "clocks.max.gr", "clocks.max.mem", "pstate", "pcie.link.gen.current", "pcie.link.width.current", "pcie.link.gen.max", "pcie.link.width.max", "compute_cap", "vbios_version", "ecc.mode.current", "ecc.errors.uncorrected.volatile.total", "ecc.errors.corrected.volatile.total", "clocks_throttle_reasons.active", "mig.mode.current", "encoder.stats.sessionCount"])
    if sc != "old" and DRV >= "550": valid.add("clocks_event_reasons.active")
    valid -= OLD
    for f in fields:
        if f not in valid:
            print('Field "%s" is not a valid field to query.\n' % f); sys.exit(2)
    loop = None
    for i, a in enumerate(args):
        if a == "-lms": loop = int(args[i + 1]) / 1000.0
        elif a == "-l": loop = float(args[i + 1])
        elif a.startswith("-l") and a[2:].isdigit(): loop = float(a[2:])
    n = 0
    while True:
        for g in gpus():
            print(", ".join(str(g[f]) for f in fields)); sys.stdout.flush()
        n += 1
        if sc == "die" and n >= 2: os.kill(os.getpid(), 9)
        if loop is None: break
        time.sleep(loop)
    sys.exit(0)
if any(a.startswith("--query-compute-apps") for a in args):
    g = gpus()
    print("GPU-1234abcd-0000-0000-0000-000000000000, 1201, /usr/bin/python3.11, 6144")
    print("GPU-1234abcd-0000-0000-0000-000000000000, 1203, /usr/local/bin/llama-server, 1536")
    print("GPU-1234abcd-0000-0000-0000-000000000000, 4242, /usr/bin/python3, [Not Available]" if sc != "noperm" else "GPU-1234abcd-0000-0000-0000-000000000000, 4242, [Insufficient Permissions], [Insufficient Permissions]")
    sys.exit(0)
if "-q" in args and "-x" in args:
    print('<?xml version="1.0" ?>\n<nvidia_smi_log>\n\t<timestamp>x</timestamp>\n\t<driver_version>%s</driver_version>\n\t<cuda_version>12.2</cuda_version>\n\t<attached_gpus>%d</attached_gpus>' % (DRV, len(gpus())))
    for g in gpus():
        print('\t<gpu id="%s">\n\t\t<product_name>%s</product_name>' % (g["pci.bus_id"], g["name"]))
        print('\t\t<processes>')
        if g["index"] == 0:
            for pid, ty, nm, mem in ((1201, "C", "/usr/bin/python3.11", "6144 MiB"), (1203, "C", "/usr/local/bin/llama-server", "1536 MiB"), (1204, "G", "/usr/lib/xorg/Xorg", "300 MiB"), (1205, "C+G", "/usr/bin/blender", "N/A")):
                print('\t\t\t<process_info>\n\t\t\t\t<pid>%d</pid>\n\t\t\t\t<type>%s</type>\n\t\t\t\t<process_name>%s</process_name>\n\t\t\t\t<used_memory>%s</used_memory>\n\t\t\t</process_info>' % (pid, ty, nm, mem))
        print('\t\t</processes>\n\t</gpu>')
    print('</nvidia_smi_log>')
    sys.exit(0)
if "--version" in args:
    print("NVIDIA-SMI version  : %s\nNVML version        : %s\nDRIVER version      : %s\nCUDA Version        : 12.2" % (DRV, DRV[:3], DRV)); sys.exit(0)
# 預設：表格表頭
print("Tue Nov 18 10:00:00 2026       \n+---------------------------------------------------------------------------------------+\n| NVIDIA-SMI %s             Driver Version: %s     CUDA Version: 12.2     |\n+-----------------------------------------+----------------------+----------------------+" % (DRV, DRV))
for g in gpus():
    print("|   %d  %-30s  Off | %s Off |                  N/A |" % (g["index"], g["name"], g["pci.bus_id"]))
