#!/usr/bin/env python3
"""
VRAMScore-Bench v0.1 — Open-Source Local AI Hardware Benchmark CLI
==================================================================
Source:  https://www.vramscore.com/bench
License: MIT (Zero external Python dependencies — stdlib only)
Privacy: 100% local execution. Does NOT upload anything automatically.

Usage:
  curl -sSL https://www.vramscore.com/bench/vramscore_bench.py | python3
  python3 vramscore_bench.py --model deepseek-r1:32b
"""

import argparse
import json
import os
import platform
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.request

STANDARD_PROMPT = (
    "Explain in clear systems-engineering terms why memory bandwidth (GB/s) "
    "governs single-stream autoregressive LLM token generation speed while "
    "tensor compute (TFLOPS) governs long-context prompt prefill. Keep the "
    "explanation concise, technical, and structured."
)


def run_cmd(cmd):
    try:
        out = subprocess.check_output(cmd, stderr=subprocess.DEVNULL, timeout=8)
        return out.decode("utf-8", errors="ignore").strip()
    except Exception:
        return ""


def detect_hardware():
    sys_os = platform.system()
    hw = {
        "os": f"{sys_os} {platform.release()}",
        "arch": platform.machine(),
        "gpu_name": "Unknown GPU",
        "backend": "CPU",
        "vram_total_mb": 0,
        "vram_peak_mb": 0,
        "driver": "unknown",
    }

    # 1. NVIDIA CUDA via nvidia-smi
    if shutil.which("nvidia-smi"):
        line = run_cmd([
            "nvidia-smi",
            "--query-gpu=name,memory.total,memory.used,driver_version",
            "--format=csv,noheader,nounits",
        ])
        if line:
            first = line.splitlines()[0]
            parts = [p.strip() for p in first.split(",")]
            if len(parts) >= 4:
                gpu_count = len(line.splitlines())
                hw["gpu_name"] = f"{gpu_count}x {parts[0]}" if gpu_count > 1 else parts[0]
                hw["backend"] = "CUDA"
                try:
                    hw["vram_total_mb"] = int(float(parts[1])) * gpu_count
                    hw["vram_peak_mb"] = int(float(parts[2])) * gpu_count
                except ValueError:
                    pass
                hw["driver"] = parts[3]
                return hw

    # 2. Apple Silicon Metal on macOS
    if sys_os == "Darwin":
        chip = run_cmd(["sysctl", "-n", "machdep.cpu.brand_string"])
        mem_bytes = run_cmd(["sysctl", "-n", "hw.memsize"])
        hw["gpu_name"] = chip or "Apple Silicon Mac"
        hw["backend"] = "Metal"
        try:
            hw["vram_total_mb"] = int(int(mem_bytes) / (1024 * 1024))
        except Exception:
            pass
        hw["driver"] = f"macOS {platform.mac_ver()[0]}"
        return hw

    # 3. AMD ROCm on Linux
    if shutil.which("rocm-smi"):
        hw["backend"] = "ROCm"
        name = run_cmd(["rocm-smi", "--showproductname"])
        if name:
            for ln in name.splitlines():
                if "Card series" in ln or "Radeon" in ln or "Instinct" in ln:
                    hw["gpu_name"] = ln.split(":")[-1].strip()
                    break
        return hw

    return hw


def http_json(url, payload=None, timeout=180):
    data = json.dumps(payload).encode("utf-8") if payload is not None else None
    headers = {"Content-Type": "application/json"} if payload is not None else {}
    req = urllib.request.Request(url, data=data, headers=headers)
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return json.loads(resp.read().decode("utf-8"))


def query_nvidia_used_mb():
    if not shutil.which("nvidia-smi"):
        return 0
    out = run_cmd(["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"])
    total = 0
    for ln in out.splitlines():
        try:
            total += int(float(ln.strip()))
        except ValueError:
            pass
    return total


def main():
    parser = argparse.ArgumentParser(description="VRAMScore-Bench v0.1 Local AI Telemetry CLI")
    parser.add_argument("--host", default=os.environ.get("OLLAMA_HOST", "http://127.0.0.1:11434"))
    parser.add_argument("--model", default="", help="Ollama model tag to test (auto-picks first installed if empty)")
    parser.add_argument("--ctx", type=int, default=8192, help="Context length num_ctx (default: 8192)")
    parser.add_argument("--tokens", type=int, default=200, help="Tokens to generate (default: 200)")
    args = parser.parse_args()

    host = args.host.rstrip("/")
    if not host.startswith("http"):
        host = f"http://{host}"

    print("\n============================================================")
    print("  VRAMScore-Bench v0.1 — Local AI Measured Telemetry CLI")
    print("  https://www.vramscore.com/bench  |  100% Local & Private")
    print("============================================================")

    hw = detect_hardware()
    print(f"Detected Hardware : {hw['gpu_name']} ({hw['backend']})")
    print(f"Memory Pool       : {round(hw['vram_total_mb'] / 1024, 1)} GB  |  Driver: {hw['driver']}")

    try:
        tags = http_json(f"{host}/api/tags", timeout=8)
    except Exception as e:
        print(f"\n[ERROR] Could not reach local Ollama at {host}: {e}")
        print("Start Ollama (`ollama serve`) or pass --host http://127.0.0.1:11434")
        sys.exit(1)

    models = [m.get("name", "") for m in tags.get("models", []) if m.get("name")]
    if not models:
        print("\n[ERROR] No Ollama models installed locally.")
        print("Pull one first, e.g.: ollama pull deepseek-r1:8b")
        sys.exit(1)

    target_model = args.model or models[0]
    if target_model not in models and args.model:
        print(f"\n[INFO] Model '{target_model}' not in /api/tags; Ollama will attempt to load it.")

    print(f"Benchmark Model   : {target_model} (ctx={args.ctx}, max_tokens={args.tokens})")
    print("\nRunning deterministic benchmark (temperature=0, seed=42)...")

    t0 = time.time()
    try:
        res = http_json(
            f"{host}/api/generate",
            payload={
                "model": target_model,
                "prompt": STANDARD_PROMPT,
                "stream": False,
                "options": {
                    "temperature": 0,
                    "seed": 42,
                    "num_ctx": args.ctx,
                    "num_predict": args.tokens,
                },
            },
            timeout=300,
        )
    except urllib.error.URLError as e:
        print(f"\n[ERROR] Inference failed: {e}")
        sys.exit(1)

    wall_s = round(time.time() - t0, 2)
    eval_count = int(res.get("eval_count", 0))
    eval_ns = int(res.get("eval_duration", 1))
    prompt_count = int(res.get("prompt_eval_count", 0))
    prompt_ns = int(res.get("prompt_eval_duration", 1))

    tg_toks = round(eval_count / max(1e-6, eval_ns / 1e9), 2)
    pp_toks = round(prompt_count / max(1e-6, prompt_ns / 1e9), 2)

    # Check active VRAM allocation via Ollama /api/ps + nvidia-smi
    vram_used_gb = round(query_nvidia_used_mb() / 1024.0, 2)
    try:
        ps = http_json(f"{host}/api/ps", timeout=5)
        for proc in ps.get("models", []):
            if proc.get("name") == target_model or target_model.split(":")[0] in proc.get("name", ""):
                sv = proc.get("size_vram", 0)
                if sv > 0:
                    vram_used_gb = round(sv / (1024 ** 3), 2)
                break
    except Exception:
        pass

    report = {
        "schema": "vramscore-bench-v0.1",
        "gpu": hw["gpu_name"],
        "backend": hw["backend"],
        "driver": hw["driver"],
        "vram_total_gb": round(hw["vram_total_mb"] / 1024.0, 1),
        "vram_used_gb": vram_used_gb,
        "model": target_model,
        "context": args.ctx,
        "gen_tok_s": tg_toks,
        "prompt_tok_s": pp_toks,
        "eval_tokens": eval_count,
        "wall_sec": wall_s,
    }

    print("\n------------------- MEASURED RESULTS -----------------------")
    print(f"  Generation Speed (tg) : {tg_toks} tok/s ({eval_count} tokens)")
    print(f"  Prompt Prefill (pp)   : {pp_toks} tok/s ({prompt_count} tokens)")
    print(f"  Measured Model VRAM   : {vram_used_gb} GB")
    print(f"  Total Wall Time       : {wall_s} s")
    print("------------------------------------------------------------")
    print("\nPaste this JSON at https://www.vramscore.com/bench to compare")
    print("against theoretical memory-bandwidth physics & generate a badge:\n")
    print(json.dumps(report))
    print("")


if __name__ == "__main__":
    main()
