#!/usr/bin/python3
"""Stand-in for nvidia-smi in the tests: answers --help-query-gpu and --query-gpu from $FAKE_NVIDIA_SMI (JSON).

The JSON holds "gpus", a list of {field: value} as nvidia-smi prints them with nounits, optionally "known",
the fields --help-query-gpu lists (default: all fields of the first GPU), and "exit"/"output" to fail.
"""
import json
import os
import sys

config = json.loads(os.environ["FAKE_NVIDIA_SMI"])
args = sys.argv[1:]
if "exit" in config:
    print(config.get("output", ""))
    sys.exit(config["exit"])

known = config.get("known") or list(config["gpus"][0])
if args == ["--help-query-gpu"]:
    print("List of valid properties to query for the switch \"--query-gpu=\":\n")
    for name in known:
        print('"%s"\nSome description.\n' % name)
    sys.exit(0)

indices = None
if args[:1] == ["-i"]:
    indices = args[1].split(",")
    args = args[2:]
fields = args[0].split("=", 1)[1].split(",")
for name in fields:
    if name not in known:
        print('Field "%s" is not a valid field to query.\n' % name)
        sys.exit(2)
for gpu in config["gpus"]:
    if indices is None or str(gpu["index"]) in indices:
        print(", ".join(str(gpu.get(name, "[N/A]")) for name in fields))
