#!/usr/bin/env python3
"""Read GPU inventory and measure an installed Flea in an isolated temporary fixture."""
import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import re
import shutil
import signal
import statistics
import subprocess
import tempfile
import time


def safe(value):
    value = re.sub(r"\S*[/\\]\S*", "[redacted]", str(value))
    return re.sub(r"[^ -~]", " ", value)[:240]


def icd_name(value):
    if re.fullmatch(r"(?:nvidia|intel|intel_hasvk|radeon|nouveau|lvp|virtio|gfxstream|freedreno|broadcom|panfrost)_icd(?:\.(?:x86_64|i686|aarch64))?\.json", value):
        return value
    return "other ICD (filename withheld)"


def read(path):
    try:
        return path.read_text().strip()
    except (OSError, UnicodeError):
        return "unknown"


def inventory():
    devices = []
    for path in sorted(Path("/sys/bus/pci/devices").glob("*")):
        try:
            display = int(read(path / "class"), 16) >> 16 == 3
        except ValueError:
            continue
        if display:
            driver = (path / "driver").resolve().name if (path / "driver").exists() else "unbound"
            version = read(Path("/sys/module") / driver / "version")
            devices.append(f"{read(path / 'vendor')}:{read(path / 'device')} {driver} {version}")
    return devices


def icds(env):
    home = Path(env.get("HOME", "/nonexistent"))
    roots = [env.get("XDG_CONFIG_HOME") or str(home / ".config"),
             env.get("XDG_DATA_HOME") or str(home / ".local/share"),
             "/etc/xdg", "/etc", "/usr/local/share", "/usr/share"]
    for key in ("XDG_CONFIG_DIRS", "XDG_DATA_DIRS"):
        roots.extend(env.get(key, "").split(":"))
    names = set()
    seen = 0
    for root in roots:
        if not root or not Path(root).is_absolute():
            continue
        for path in (Path(root) / "vulkan/icd.d").glob("*.json"):
            seen += 1
            if seen > 256:
                return ["inventory exceeds 256 manifests"]
            names.add(icd_name(path.name))
    return sorted(names)


def cleanup(root):
    if not root.is_absolute() or root.parent != Path("/tmp").resolve():
        raise RuntimeError("temporary root guard refused cleanup")
    if not root.name.startswith("flea-gpu-report-") or not (root / ".flea-test-sandbox").is_file():
        raise RuntimeError("temporary marker guard refused cleanup")
    shutil.rmtree(root)


def decode(stderr):
    adapter, frames, policy = {}, {}, "unavailable"
    available = []
    selected = None
    opened = None
    changed = False
    for line in stderr.splitlines():
        snapshot = re.fullmatch(r'GPUI_RENDERER backend=(\w+) adapter=("(?:[^"\\]|\\.)*") driver=("(?:[^"\\]|\\.)*") driver_info=("(?:[^"\\]|\\.)*") software=(true|false) .+', line)
        if snapshot:
            backend, name, driver, version, cpu = snapshot.groups()
            adapter = dict(name=json.loads(name), driver=json.loads(driver),
                           version=json.loads(version), cpu=cpu == "true",
                           backend=backend, device_type="Cpu" if cpu == "true" else "hardware (exact type unavailable)")
            opened = (adapter["name"], "Gl" if backend.lower() == "gl" else "Vulkan")
        # S6's ordinary stderr line is authoritative for the backend of this adapter.
        backend_line = re.fullmatch(r'flea: (?:the window starts on (Vulkan|OpenGL)|Vulkan is unusable, .+, so the window starts on (OpenGL)) \((.+)\)', line)
        if backend_line:
            backend = backend_line[1] or backend_line[2]
            selected = (backend_line[3].strip('"'), "Gl" if backend == "OpenGL" else backend)
            changed |= opened is not None and selected != opened
            if adapter and adapter.get("name") == selected[0]:
                adapter["backend"] = selected[1]
                opened = selected
        details = re.fullmatch(r"flea-graphics:   - (.+) \(vendor=0x[0-9a-f]+, device=0x[0-9a-f]+, backend=(Vulkan|Gl), type=(Cpu|DiscreteGpu|IntegratedGpu|VirtualGpu|Other)\)", line)
        if details:
            available.append(details.groups())
        choice = re.fullmatch(r"flea-graphics: Selected GPU \(passed configuration test\): (.+) \((Vulkan|Gl)\)", line)
        if choice:
            selected = choice.groups()
            changed |= opened is not None and selected != opened
        if line.startswith("FLEA_GPU_ADAPTER "):
            previous = adapter
            adapter = json.loads(line[len("FLEA_GPU_ADAPTER "):])
            if not isinstance(adapter, dict):
                raise ValueError("candidate adapter diagnostics are not an object")
            for key in ("name", "driver", "version", "backend", "device_type", "build"):
                if key in adapter and not isinstance(adapter[key], str):
                    raise ValueError("candidate adapter diagnostics have an invalid text field")
            if "cpu" in adapter and type(adapter["cpu"]) is not bool:
                raise ValueError("candidate CPU diagnostics are not a Boolean")
            if previous and type(previous.get("cpu")) is bool and type(adapter.get("cpu")) is bool:
                changed |= (previous.get("name"), previous["cpu"]) != (adapter.get("name"), adapter["cpu"])
            opened = selected
            if selected is not None and adapter.get("name") == selected[0]:
                adapter["backend"] = selected[1]
            if "device_type" not in adapter and type(adapter.get("cpu")) is bool:
                adapter["device_type"] = "Cpu" if adapter["cpu"] else "hardware (exact type unavailable)"
        elif line.startswith("FLEA_GPU_FRAMES "):
            frames = json.loads(line[len("FLEA_GPU_FRAMES "):])
        elif line.startswith("flea-gpu-policy: "):
            raw = line[len("flea-gpu-policy: "):]
            field = re.match(r'excluded=("(?:[^"\\]|\\.)*")', raw)
            try:
                excluded = json.loads(field[1]) if field else None
            except ValueError:
                excluded = None
            names = ",".join(icd_name(name) for name in excluded.split(",")) if excluded else "none" if excluded == "" else "names withheld"
            operator = "yes" if "operator_icd=true" in raw else "no"
            idle = "yes" if "nvidia_idle_disabled=true" in raw else "no" if "nvidia_idle_disabled=false" in raw else "unknown"
            policy = f"excluded={names}; operator ICD override={operator}; idle NVIDIA drivers disabled={idle}; preference=compositor GPU"
    if not isinstance(adapter, dict) or not isinstance(frames, dict):
        raise ValueError("candidate diagnostics are not objects")
    if not isinstance(frames.get("intervals_ms", []), list):
        raise ValueError("candidate frame timings are not a list")
    for name, backend, kind in available:
        actual_backend = adapter.get("backend")
        if name == adapter.get("name") and (kind == "Cpu") == adapter.get("cpu") and (actual_backend is None or actual_backend.lower() == backend.lower()) and (opened is None or opened == (name, backend)):
            adapter.update(backend=backend, device_type=kind)
            break
    if changed or (selected is not None and ((opened is not None and selected != opened) or adapter.get("name") != selected[0])):
        adapter["changed"] = True
        adapter["cpu"] = None
    return adapter, frames, policy


def scroll_covered(frames):
    values = frames.get("intervals_ms", [])
    measured = [value for value in values if type(value) in (int, float) and math.isfinite(value) and value > 0]
    return len(measured) >= 2 and 4000 <= sum(measured) <= 6000


def summary(gpus, session, adapter, frames, status):
    intervals = frames.get("intervals_ms", [])
    intervals = sorted(value for value in intervals if type(value) in (int, float) and math.isfinite(value) and value > 0)
    first = frames.get("first_ms")
    first = f"{first:.2f} ms" if type(first) in (int, float) and math.isfinite(first) and first >= 0 else "unavailable (no timed presentation feedback)"
    times = "unavailable (no presentation feedback)"
    if len(intervals) >= 2:
        times = f"median {statistics.median(intervals):.2f} ms, p95 {intervals[math.ceil(.95 * len(intervals)) - 1]:.2f} ms"
    cpu = "YES, CPU RENDERER IN USE" if adapter.get("cpu") is True else "no" if adapter.get("cpu") is False else "unknown"
    return "\n".join([
        "FLEA GPU REPORT",
        "Candidate: " + safe(adapter.get("build", "unknown")),
        "GPU: " + (", ".join(map(safe, gpus)) or "none detected"),
        "Driver/version: " + safe(adapter.get("driver", "unknown")) + " " + safe(adapter.get("version", "unknown")),
        "Session: " + session,
        "Adapter opened: " + safe(adapter.get("name", "unavailable")),
        "Adapter type/backend: " + safe(adapter.get("device_type", "unavailable")) + " / " + safe(adapter.get("backend", "unavailable")),
        "CPU renderer: " + cpu,
        "First frame: " + first,
        "Frame time (5-second scroll): " + times,
        "Result: " + status,
    ])


def run(binary):
    binary = str(Path(binary).absolute())
    original = dict(os.environ)
    gpus = inventory()
    manifests = icds(original)
    session = "Wayland" if original.get("WAYLAND_DISPLAY") else "X11" if original.get("DISPLAY") else "none"
    root = Path(tempfile.mkdtemp(prefix="flea-gpu-report-", dir="/tmp")).resolve()
    (root / ".flea-test-sandbox").write_text("Flea GPU report temporary root\n")
    process = None
    try:
        isolation = shutil.which("bwrap")
        if not isolation:
            print(summary(gpus, session, {}, {}, "FAILED: Flea runtime dependency bubblewrap is missing"))
            return 1
        allowed = {"PATH", "LANG", "LC_ALL", "DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY",
                   "FLEA_VK_PIN", "FLEA_VK_DISABLE", "ZED_DEVICE_ID", "DRI_PRIME",
                   "GALLIUM_DRIVER", "LIBGL_ALWAYS_SOFTWARE", "LIBGL_ALWAYS_INDIRECT",
                   "EGL_PLATFORM", "__GLX_VENDOR_LIBRARY_NAME", "__NV_PRIME_RENDER_OFFLOAD",
                   "__NV_PRIME_RENDER_OFFLOAD_PROVIDER", "__VK_LAYER_NV_optimus"}
        env = {key: value for key, value in original.items()
               if key in allowed or key.startswith(("VK_", "MESA_", "__GL_"))}
        env.update(FLEA_GPU_REPORT="1", FLEA_GPUI_CAPTURE="1", FLEA_FRONTEND="gpui",
                   FLEA_BIN=binary, HOME=str(root / "home"))
        (root / "home").mkdir(mode=0o700)
        (root / "shm").mkdir(mode=0o700)
        for key in list(env):
            if key in ("FLEA_UNLOCK", "FLEA_PICKER", "FLEA_PATH", "FLEA_SELECT") or key.startswith("FLEA_GUI_BENCH_"):
                del env[key]
        for key, name in (("XDG_CONFIG_HOME", "config"), ("XDG_CACHE_HOME", "cache"),
                          ("XDG_DATA_HOME", "data"), ("XDG_STATE_HOME", "state"),
                          ("XDG_RUNTIME_DIR", "runtime"), ("TMPDIR", "tmp")):
            directory = root / name
            directory.mkdir(mode=0o700)
            env[key] = str(directory)
        fontconfig = Path(original.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))) / "fontconfig"
        if fontconfig.is_dir():
            shutil.copytree(fontconfig, root / "config/fontconfig", symlinks=True)
        if env.get("WAYLAND_DISPLAY") and not Path(env["WAYLAND_DISPLAY"]).is_absolute():
            env["WAYLAND_DISPLAY"] = str(Path(original.get("XDG_RUNTIME_DIR", "/run/user/" + str(os.getuid()))) / env["WAYLAND_DISPLAY"])
        env["__GL_SHADER_DISK_CACHE_PATH"] = str(root / "cache/nvidia")
        fixture = root / "rows"
        fixture.mkdir()
        for index in range(10_000):
            (fixture / f"row-{index:05d}.txt").touch()
        env["FLEA_GPU_REPORT_START_NS"] = str(time.monotonic_ns())
        command = [isolation, "--ro-bind", "/", "/", "--tmpfs", "/run",
                   "--bind", str(root), str(root),
                   "--dev-bind", "/dev", "/dev", "--proc", "/proc", "--unshare-net",
                   "--bind", str(root / "shm"), "/dev/shm",
                   "--unshare-pid", "--unshare-ipc", "--die-with-parent", "--new-session"]
        for key, default in (("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share")):
            original_vulkan = Path(original.get(key) or str(Path.home() / default)) / "vulkan"
            if original_vulkan.is_dir():
                command.extend(["--ro-bind", str(original_vulkan), str(Path(env[key]) / "vulkan")])
        if env.get("WAYLAND_DISPLAY"):
            socket = env["WAYLAND_DISPLAY"]
            env["WAYLAND_DISPLAY"] = str(root / "runtime/wayland")
            command.extend(["--ro-bind", socket, env["WAYLAND_DISPLAY"]])
        if env.get("DISPLAY"):
            authority = Path(original.get("XAUTHORITY") or str(Path.home() / ".Xauthority")).absolute()
            if authority.is_file():
                env["XAUTHORITY"] = str(root / "runtime/xauthority")
                command.extend(["--ro-bind", str(authority), env["XAUTHORITY"]])
        command.extend(["--", binary, "--gui", str(fixture)])
        process = subprocess.Popen(command, env=env, cwd=root,
                                   stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
                                   text=True, start_new_session=True)
        terminated = False
        try:
            _, stderr = process.communicate(timeout=25)
        except subprocess.TimeoutExpired:
            terminated = True
            os.killpg(process.pid, signal.SIGKILL)
            _, stderr = process.communicate(timeout=3)
        try:
            adapter, frames, policy = decode(stderr)
        except (ValueError, TypeError):
            adapter, frames, policy = {}, {}, "invalid diagnostics"
        complete = (process.returncode == 0 and frames.get("complete") is True
                    and frames.get("ready") is True
                    and isinstance(adapter.get("name"), str) and bool(adapter["name"]))
        known_cpu = type(adapter.get("cpu")) is bool
        first = frames.get("first_ms")
        timed = type(first) in (int, float) and math.isfinite(first) and first >= 0 and len(frames.get("intervals_ms", [])) >= 2
        covered = scroll_covered(frames)
        if complete and timed and covered and known_cpu and not adapter.get("changed"):
            status = "complete"
        elif complete and adapter.get("changed"):
            status = "PARTIAL: adapter changed during the run; CPU state needs rechecking"
        elif complete and not known_cpu:
            status = "PARTIAL: actual CPU renderer state is unavailable"
        elif complete and timed and not covered:
            status = "PARTIAL: presentation samples do not cover the five-second scroll"
        elif complete:
            status = "PARTIAL: window opened and scrolled; presentation timing unavailable"
        elif terminated and adapter:
            status = "PARTIAL: actual adapter opened; candidate lacks five-second scroll diagnostics"
        else:
            status = f"FAILED: candidate exit {process.returncode}; window/scroll diagnostics incomplete"
        print("ICDs present: " + (", ".join(manifests) or "none"))
        with open(binary, "rb") as executable:
            print("Candidate binary SHA256: " + hashlib.file_digest(executable, "sha256").hexdigest())
        print("Launch policy: " + policy)
        print(summary(gpus, session, adapter, frames, status))
        return 0 if complete and timed and covered and known_cpu and not adapter.get("changed") else 1
    finally:
        if process is not None:
            try:
                os.killpg(process.pid, signal.SIGKILL)
            except ProcessLookupError:
                pass
            try:
                process.wait(timeout=3)
            except subprocess.TimeoutExpired:
                if process.stderr:
                    process.stderr.close()
        cleanup(root)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--flea", default="flea", help="installed candidate executable (default: flea)")
    args = parser.parse_args()
    binary = shutil.which(args.flea)
    if not binary:
        print("FLEA GPU REPORT\nResult: FAILED: install the Flea candidate first")
        return 1
    try:
        return run(binary)
    except (OSError, RuntimeError, ValueError, TypeError):
        print("FLEA GPU REPORT\nResult: FAILED: could not prepare or launch the isolated report")
        return 1


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