"""Serve one pinned checkpoint on the benchmark laptop and collect peak residency."""
import ctypes
import json
import pathlib
import subprocess
import sys
import time
from ctypes import wintypes

ROOT = pathlib.Path(__file__).resolve().parent
MODEL = sys.argv[1]
FILE = {"q36": "Qwen3.6-35B-A3B-UD-IQ2_M.gguf", "q4": "Qwen4-35B-A3B-UD-IQ2_M-00001-of-00002.gguf"}[MODEL]
missing = [p for p in ([FILE] if MODEL == 'q36' else [FILE,FILE.replace('00001-of','00002-of')]) if not (ROOT/p).exists()]
if missing:
    raise SystemExit(f"Waiting for verified weights: {missing}")
class Counters(ctypes.Structure):
    _fields_ = [('cb',wintypes.DWORD),('PageFaultCount',wintypes.DWORD)] + [(k,ctypes.c_size_t) for k in ['PeakWorkingSetSize','WorkingSetSize','QuotaPeakPagedPoolUsage','QuotaPagedPoolUsage','QuotaPeakNonPagedPoolUsage','QuotaNonPagedPoolUsage','PagefileUsage','PeakPagefileUsage']]
def gpu():
    return int(subprocess.check_output(['nvidia-smi','--query-gpu=memory.used','--format=csv,noheader,nounits'],text=True).splitlines()[0])
ctypes.windll.kernel32.SetThreadExecutionState(0x80000001)
cmd=[str(ROOT/'runtime-b12973'/'llama-server.exe'),'-m',str(ROOT/FILE),'--alias',MODEL,'-c','32768','-np','1','--host','127.0.0.1','--port','18265','--jinja','-lv','4','--no-webui','--device','Vulkan0','--fit','on','--fit-target','768','--lazy-mode','on','--cache-ram','0','-fa','on','--reasoning','off','--no-context-shift']
if MODEL == 'q4':
    # The Qwen4 template accepts 'off'. Global --reasoning off injects 'none' and fails before inference.
    cmd[cmd.index('--reasoning')+1]='auto'
    cmd.extend(['--chat-template-kwargs',json.dumps({'enable_thinking':False,'reasoning_effort':'off'}),'--reasoning-budget','0'])
run=ROOT/MODEL;run.mkdir(exist_ok=True)
session=str(int(time.time()))
with (run/(session+'-server.log')).open('w') as log:
    baseline=gpu(); start=time.monotonic()
    proc=subprocess.Popen(cmd,stdout=log,stderr=subprocess.STDOUT)
    handle=ctypes.windll.kernel32.OpenProcess(0x410,False,proc.pid)
    peak_ram=peak_gpu=0
    try:
        while proc.poll() is None:
            values=Counters();values.cb=ctypes.sizeof(values)
            if ctypes.windll.psapi.GetProcessMemoryInfo(handle,ctypes.byref(values),values.cb):
                peak_ram=max(peak_ram,values.PeakWorkingSetSize)
            peak_gpu=max(peak_gpu,gpu())
            rec=dict(pid=proc.pid,command=cmd,elapsed_s=round(time.monotonic()-start,2),peak_working_set_bytes=peak_ram,baseline_gpu_mib=baseline,peak_device_used_mib=peak_gpu,sample_seconds=2)
            tmp=run/(session+'-memory.tmp');tmp.write_text(json.dumps(rec));tmp.replace(run/(session+'-memory.json'))
            if (run/'stop').exists():
                (run/'stop').unlink();break
            time.sleep(2)
    finally:
        if proc.poll() is None:
            proc.terminate();proc.wait(timeout=50)
        ctypes.windll.kernel32.CloseHandle(handle)
        ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
