import json, re, subprocess, tempfile, zipfile, os
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
QA=ROOT/'qa_screenshots'; QA.mkdir(exist_ok=True)
report={'version':'rc52','checks':{},'errors':[],'warnings':[]}
# JSON
json_ok=[]
for p in ROOT.rglob('*.json'):
    try:
        json.loads(p.read_text(encoding='utf-8'))
        json_ok.append(str(p.relative_to(ROOT)))
    except Exception as e:
        report['errors'].append(f'JSON {p}: {e}')
report['checks']['jsonFilesOk']=len(json_ok)
# JS files syntax
js_ok=[]
for p in ROOT.rglob('*.js'):
    r=subprocess.run(['node','--check',str(p)],capture_output=True,text=True)
    if r.returncode==0: js_ok.append(str(p.relative_to(ROOT)))
    else: report['errors'].append(f'JS syntax {p}: {r.stderr[:300]}')
report['checks']['jsFilesOk']=len(js_ok)
# HTML inline scripts syntax
html_inline=[]
for p in [ROOT/'preview.html', ROOT/'tools/video_screen_pose_capture_lab.html', ROOT/'tools/visual_review_correction_lab.html']:
    if not p.exists():
        report['errors'].append(f'Missing expected HTML {p.relative_to(ROOT)}')
        continue
    s=p.read_text(encoding='utf-8')
    for i,m in enumerate(re.finditer(r'<script(?:[^>]*)>(.*?)</script>', s, re.S|re.I)):
        code=m.group(1).strip()
        if not code: continue
        with tempfile.NamedTemporaryFile('w',suffix='.js',delete=False) as f:
            f.write(code); tmp=f.name
        r=subprocess.run(['node','--check',tmp],capture_output=True,text=True)
        os.unlink(tmp)
        if r.returncode==0: html_inline.append(f'{p.relative_to(ROOT)}#{i}')
        else: report['errors'].append(f'Inline JS {p.relative_to(ROOT)}#{i}: {r.stderr[:300]}')
report['checks']['htmlInlineScriptsOk']=len(html_inline)
# PHP lint
php_ok=[]
for p in ROOT.rglob('*.php'):
    r=subprocess.run(['php','-l',str(p)],capture_output=True,text=True)
    if r.returncode==0: php_ok.append(str(p.relative_to(ROOT)))
    else: report['errors'].append(f'PHP lint {p}: {r.stdout} {r.stderr}')
report['checks']['phpFilesOk']=len(php_ok)
# Required links/tool
preview=(ROOT/'preview.html').read_text(encoding='utf-8')
tool=(ROOT/'tools/video_screen_pose_capture_lab.html').read_text(encoding='utf-8')
report['checks']['testcenterHasVideoToolLink']='tools/video_screen_pose_capture_lab.html?v=rc52' in preview
report['checks']['previewCacheBumped']='v97-rc52' in preview and 'v97-rc51' not in preview
report['checks']['videoToolExists']=(ROOT/'tools/video_screen_pose_capture_lab.html').exists()
report['checks']['videoToolHasScreenCapture']='getDisplayMedia' in tool
report['checks']['videoToolUsesVideoMode']="runningMode:'VIDEO'" in tool or 'runningMode:"VIDEO"' in tool
report['checks']['videoToolUsesDetectForVideo']='detectForVideo' in tool
report['checks']['videoToolExportsSchema']='rc52-video-screen-pose-capture-v1' in tool
report['checks']['videoToolNoVideoRetention']='videoSaved:false' in tool and 'videoFramesSaved:false' in tool
report['checks']['staticScreenshotsExist']=all((QA/f'rc52_{n}_static_qa.png').exists() for n in ['mobile','ipad','desktop'])
# atlas basic
atlas=ROOT/'assets/data/image-admin/pose-atlas-packs.json'
if atlas.exists():
    data=json.loads(atlas.read_text(encoding='utf-8'))
    poses=data.get('poses',[])
    sprites=0; missing=[]
    for pose in poses:
        for aid,a in (pose.get('athletes') or {}).items():
            sprites+=1
            src=a.get('src')
            if src and not (ROOT/src).exists(): missing.append(src)
    report['checks']['poseKeys']=len(poses)
    report['checks']['athleteSprites']=sprites
    report['checks']['missingSprites']=len(missing)
else:
    report['warnings'].append('pose-atlas-packs.json not found')
# required bools
for k,v in list(report['checks'].items()):
    if isinstance(v,bool) and not v: report['errors'].append('Failed check '+k)
report['ok']=not report['errors']
out=QA/'rc52_package_qa_report.json'
out.write_text(json.dumps(report,indent=2,ensure_ascii=False),encoding='utf-8')
print(json.dumps(report,indent=2,ensure_ascii=False))
raise SystemExit(0 if report['ok'] else 1)
