#!/usr/bin/env python3
import base64, json, os, socketserver, threading, http.server, time, urllib.parse, subprocess, shutil
from pathlib import Path
from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError

ROOT = Path('/mnt/data/nex_v300_grip_entry_contract/NEXT11_V300_GRIP_ENTRY_CONTRACT_REHYDRATED_ROOT')
OUT = Path('/mnt/data/nex_v300_grip_entry_contract/diagnostics/V300_BROWSER_RUNTIME_AUDIT.json')
SHOT_DIR = Path('/mnt/data/nex_v300_grip_entry_contract/diagnostics/v300_browser_screens')
SHOT_DIR.mkdir(parents=True, exist_ok=True)

class QuietHandler(http.server.SimpleHTTPRequestHandler):
    def log_message(self,*args): pass

def start_server():
    os.chdir(ROOT)
    srv=socketserver.TCPServer(('127.0.0.1',0), QuietHandler)
    threading.Thread(target=srv.serve_forever,daemon=True).start()
    return srv, srv.server_address[1]

EVAL_JS = """() => {
  const keys=Object.keys(window).filter(k=>k.startsWith('__NEXPROD01')).sort();
  const grip=window.__NEXPROD01_GRIP_SOLVER_V1 || null;
  const gate=window.__NEXPROD01_V297_PREFINGER_CHILD_LAYER_GATE || null;
  const v110=window.__NEXPROD01_V110_DISTAL_GRIP_COUPLED || null;
  const v151=window.__NEXPROD01_V151_ACTUAL_MESH_TRUTH || null;
  const probe=window.__NEXPROD01_V93_ACTIVE_HAND_CONTROL_PROBE || null;
  const debug=window.__NEXPROD01_DEBUG_SCENE || null;
  const model=debug?.model || null;
  let boneCount=null, skinnedMeshCount=0, canvasCount=document.querySelectorAll('canvas').length;
  try { if(model){ boneCount=0; model.traverse(o=>{ if(o?.isBone) boneCount++; if(o?.isSkinnedMesh) skinnedMeshCount++; }); } } catch(e) {}
  return {href:location.href, ready:document.readyState, hasDebug:!!debug, hasModel:!!model, boneCount, skinnedMeshCount, canvasCount, windowMarkers:keys, markerCount:keys.length, gripSolverV1:grip, v297FingerGate:gate, v110DistalGrip:v110, v151MeshTruth:v151, activeHandProbe:probe, bodyText:(document.body?.innerText||'').slice(0,1000)};
}"""

def summarize(final):
    final=final or {}
    grip=final.get('gripSolverV1') if isinstance(final,dict) else None
    gate=final.get('v297FingerGate') if isinstance(final,dict) else None
    probe=final.get('activeHandProbe') if isinstance(final,dict) else None
    v151=final.get('v151MeshTruth') if isinstance(final,dict) else None
    stage_gate=(((grip or {}).get('stages') or {}).get('v297EntryFrameGate') or {}) if isinstance(grip,dict) else {}
    v300_gate=(((grip or {}).get('stages') or {}).get('v300PalmFrameGate') or {}) if isinstance(grip,dict) else {}
    v300_roll=(((grip or {}).get('stages') or {}).get('v300ForearmAxisSecondPalmRoll') or {}) if isinstance(grip,dict) else {}
    v300_meet=(((grip or {}).get('stages') or {}).get('v300ObjectMeetGate') or {}) if isinstance(grip,dict) else {}
    return {
      'hasDebug': bool(final.get('hasDebug')),
      'hasModel': bool(final.get('hasModel')),
      'boneCount': final.get('boneCount'),
      'skinnedMeshCount': final.get('skinnedMeshCount'),
      'canvasCount': final.get('canvasCount'),
      'hasGripSolverV1': bool(grip),
      'gripSchema': grip.get('schema') if isinstance(grip,dict) else None,
      'gripSide': grip.get('side') if isinstance(grip,dict) else None,
      'gripApplied': grip.get('applied') if isinstance(grip,dict) else None,
      'gripPass': grip.get('pass') if isinstance(grip,dict) else None,
      'gripReason': grip.get('reason') if isinstance(grip,dict) else None,
      'gripStatus': grip.get('status') if isinstance(grip,dict) else None,
      'preFingerReady': grip.get('preFingerReady') if isinstance(grip,dict) else None,
      'entryGateSchema': stage_gate.get('schema'),
      'entryGate': stage_gate.get('gate'),
      'entryGatePass': stage_gate.get('pass'),
      'entrySignedOutsideM': stage_gate.get('signedOutsideM'),
      'entryRequiredOutwardShiftM': stage_gate.get('requiredOutwardShiftM'),
      'v300PalmFrameGateSchema': v300_gate.get('schema'),
      'v300PalmFrameGatePass': v300_gate.get('pass'),
      'v300RollPass': v300_roll.get('pass'),
      'v300RollDeg': v300_roll.get('rollDeg'),
      'v300ObjectMeetM': v300_meet.get('meetM'),
      'v300ObjectMeetPass': v300_meet.get('pass'),
      'fingerGateSchema': gate.get('schema') if isinstance(gate,dict) else None,
      'fingerBlocked': gate.get('blocked') if isinstance(gate,dict) else None,
      'fingerActive': gate.get('active') if isinstance(gate,dict) else None,
      'probeSide': probe.get('side') if isinstance(probe,dict) else None,
      'meshTruthSide': v151.get('side') if isinstance(v151,dict) else None,
    }

cases=[
  {'name':'right','caseId':'v94_right_full','exercise':'hurdle-stretch','phase':0.75},
  {'name':'left','caseId':'v94_left_full','exercise':'hurdle-stretch','phase':0.25},
]

srv, port = start_server()
results=[]
errors=[]
try:
  with sync_playwright() as p:
    env=os.environ.copy(); env['LIBGL_ALWAYS_SOFTWARE']='1'; env['VK_ICD_FILENAMES']='/usr/lib/chromium/vk_swiftshader_icd.json'; env['DISPLAY']=''
    browser=p.chromium.launch(executable_path='/usr/bin/chromium',headless=True,env=env,args=['--no-sandbox','--disable-dev-shm-usage','--ignore-gpu-blocklist','--enable-webgl','--enable-webgl2','--enable-unsafe-swiftshader','--disable-gpu-sandbox','--ozone-platform=headless','--use-gl=angle','--use-angle=swiftshader-webgl','--remote-allow-origins=*'])
    context=browser.new_context(viewport={'width':1280,'height':900}, device_scale_factor=1)
    for case in cases:
      page=context.new_page()
      page.on('console', lambda msg: None)
      params={'exercise':case['exercise'],'caseId':case['caseId'],'phase':str(case['phase']),'play':'0','debug':'0','visualMode':'nex','nativeRuntimeParity':'1','nativeSkin':'1','skinPreset':'freeridehuman','readyTimeoutMs':'12000','hostLifecycle':'v300-grip-entry-contract-browser-audit','build':'NEXPROD01_RUNTIME_V300_GRIP_ENTRY_CONTRACT_REHYDRATED_2026_08_19','safeBoot':'0','lowPower':'1','pixelRatioCap':'1.15','antialias':'1','maxFPS':'24','staticAfterReady':'0','idleSleepAfterReady':'0','v':'V300_'+case['name']}
      url=f'http://127.0.0.1:{port}/assets/nexprod/nexprod01-player.html?'+urllib.parse.urlencode(params)
      nav_error=None
      try:
        page.goto(url, wait_until='domcontentloaded', timeout=15000)
      except Exception as e:
        nav_error=repr(e)
      polls=[]; final=None
      for i in range(6):
        page.wait_for_timeout(1000)
        try:
          val=page.evaluate(EVAL_JS)
        except Exception as e:
          polls.append({'t':i+1,'evalError':repr(e)})
          continue
        final=val
        polls.append({'t':i+1,'hasDebug':val.get('hasDebug'),'hasModel':val.get('hasModel'),'boneCount':val.get('boneCount'),'markerCount':val.get('markerCount'),'gripSchema':(val.get('gripSolverV1') or {}).get('schema'),'fingerGateSchema':(val.get('v297FingerGate') or {}).get('schema')})
        if val.get('hasModel') and val.get('gripSolverV1'):
          page.wait_for_timeout(1000)
          final=page.evaluate(EVAL_JS)
          break
      shot=str(SHOT_DIR / f"V300_{case['name']}_contract_player.png")
      try: page.screenshot(path=shot, full_page=False, timeout=5000)
      except Exception: shot=None
      results.append({'case':case,'url':url,'navigationError':nav_error,'polls':polls,'final':final,'screenshot':shot,'summary':summarize(final)})
      page.close()
    browser.close()
finally:
  srv.shutdown(); srv.server_close()

audit={'schema':'NEXT11_V300_BROWSER_RUNTIME_AUDIT','generatedAt':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'root':str(ROOT),'cases':results}
audit['passBrowserRuntime']=all(r['summary']['hasModel'] and r['summary']['hasGripSolverV1'] and r['summary']['fingerGateSchema']=='NEXPROD01_V297_PREFINGER_CHILD_LAYER_GATE' and r['summary']['fingerBlocked'] is True for r in results)
audit['passSideDiagnostics']=all((r['summary']['probeSide'] in (None,r['summary']['gripSide'])) and (r['summary']['meshTruthSide'] in (None,r['summary']['gripSide'])) for r in results)
OUT.write_text(json.dumps(audit,indent=2),encoding='utf-8')
print(json.dumps({'out':str(OUT),'passBrowserRuntime':audit['passBrowserRuntime'],'passSideDiagnostics':audit['passSideDiagnostics'],'summaries':[r['summary'] for r in results]},indent=2))
