"""New round7 ptunnel readback; login/GET/preview only, never test annotations."""
from contextlib import closing
import hashlib
import os
from pathlib import Path
import sys

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.cluster_targets import digest
from pallet.mask_model_training_data import read,write,jsonl,require
from pallet.mask_class_note_integration import snapshot_db
from pallet.pallet_description_round7_data import ROOT,sources_current
from pallet.pallet_description_round7_release import REVIEW_SETS,RELEASE
from serve_pallet_description_round7 import runtime
from check_mask_under50_ui import wait_value
from check_mask_taxonomy_keyboard_ui import keypress
from reload_mask_taxonomy_keyboard_ui import state


def verify():
    import requests
    os.environ.setdefault('PLAYWRIGHT_NODEJS_PATH','/tmp/opencode/pallet_review_browser_tools/node');sys.path.insert(0,'/tmp/opencode/pallet_review_pw132')
    from playwright.sync_api import sync_playwright
    key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip();errors=[];blocked=[];results={}
    for mode,s in REVIEW_SETS.items():
        before=RELEASE/mode/'before_public.sqlite3'
        if not before.exists():snapshot_db(s['reviews']/'mask_reviews.sqlite3',before)
    with sync_playwright() as pw:
        browser=pw.chromium.launch(executable_path='/tmp/opencode/pallet_pose_browser/chrome-linux64/chrome',headless=True,args=['--no-sandbox','--disable-dev-shm-usage','--disable-gpu','--disable-software-rasterizer','--disable-features=VizDisplayCompositor'])
        for mode,s in REVIEW_SETS.items():
            folder=RELEASE/mode;url=runtime.configured_route(mode)['url'];props=jsonl(s['root']/'proposals.jsonl');classes=[];viewports=[]
            with requests.Session() as http:
                http.headers.update({'X-Review-Request':'1','Origin':url});require(http.get(url+'/api/review/catalog',timeout=60).status_code==401,'Catalog authentication missing')
                require(http.post(url+'/api/review/login',json=dict(key=key),timeout=60).status_code==200,'Public login failed')
                cookie=next(c for c in http.cookies if c.name=='pallet_joint_description_'+mode);require(cookie.has_nonstandard_attr('HttpOnly'),'Public HttpOnly cookie missing')
                catalog=http.get(url+'/api/review/catalog',timeout=60).json();require({p['target_key'] for p in props}=={p['target_key'] for p in catalog['targets']},'Wrong public catalog')
                health=http.get(url+'/healthz',timeout=60).json();require(health['publication_version']==s['namespace'] and health['structure_replace_batch_enabled'] and health['source_guard']['parallel_full_content'],'Wrong public app/guard')
                for n,h in read(folder/'manifest.json')['assets'].items():
                    r=http.get(url+'/'+n,timeout=60);require(r.status_code==200 and hashlib.sha256(r.content).hexdigest()==h,'Public resources differ')
                for cls in sorted({p['class_id'] for p in props}):
                    p=next(p for p in props if p['class_id']==cls);v=http.get(url+'/api/review/targets/'+p['target_key'],timeout=60).json()
                    require(v['source_current'] and v['proposal']==p and v['binding']==digest(s['root']/'manifest.json'),'Public target source binding differs');classes.append(cls)
                if mode=='existing':
                    p=http.get(url+'/api/review/triage-policy',timeout=60).json();require(p['policy_sha256']==digest(folder/'policy.json') and p['policy']['actual_audit_count']==50,'Bounded policy mismatch')
                for n in ('proposals.jsonl','mask_reviews.sqlite3','access_key.txt'):require(http.get(url+'/'+n,timeout=60).status_code==404,'Private path exposed')
            for width,height in ((1400,1000),(390,844)):
                context=browser.new_context(viewport=dict(width=width,height=height),is_mobile=width==390,has_touch=width==390)
                def protect(route):
                    r=route.request
                    if r.method in ('GET','HEAD') or r.method=='POST' and r.url in (url+'/api/review/login',url+'/api/review/structure-replace-batch/preview'):route.continue_()
                    else:blocked.append(dict(method=r.method,url=r.url));route.abort()
                context.route('**/*',protect);page=context.new_page();page.on('pageerror',lambda e:errors.append(str(e)))
                try:
                    page.goto(url,wait_until='domcontentloaded',timeout=60000);page.locator('#key').fill(key);page.locator('#loginButton').click();wait_value(page,'window.taxonomyDiagnostics&&taxonomyDiagnostics().loaded&&!document.getElementById("main").hidden')
                    default=page.locator('#cards button').count()
                    if mode=='existing':
                        require(default==read(ROOT/'review_priority_selection.json')['required'],'Wrong default required view: '+str(default))
                        require(not page.locator('#triageFilter option[value="class13-recheck"]').count(),'Finished Class13 temporary scope reopened');page.locator('#triageFilter').select_option('all')
                    page.locator('#stateFilter').select_option('all');page.locator('#classFilter').select_option('');require(page.locator('#cards button').count()==len(props),'All original task records hidden')
                    page.locator('#cards button').nth(1).click();wait_value(page,'!!taxonomyDiagnostics().detail&&!taxonomyDiagnostics().opening')
                    require(page.locator('#reviewer').input_value()=='复核人1' and 'Ctrl / ⌘ + S 保存并标记已复核（不切图）' in page.locator('#keyboardHelp').inner_text(),'Reviewer or CtrlS policy changed')
                    require(page.locator('#draft').get_attribute('aria-keyshortcuts') is None,'Draft still claims CtrlS')
                    if mode=='existing':require(page.evaluate('document.getElementById("descriptionPanel").getBoundingClientRect().bottom<=document.getElementById("triageReason").closest("section").getBoundingClientRect().top'),'Description-first order lost')
                    page.locator('#structureReplaceOld').fill('SYNTHETIC ABSENT PUBLIC READ ONLY');page.locator('#structureReplaceNew').fill('NEVER APPLY');page.locator('#structureReplace').click();page.locator('#structureReplacePreview').wait_for(state='visible',timeout=60000)
                    require(f'共{len(props)}项' in page.locator('#structureReplaceScope').inner_text(),'Read-only replacement scope wrong');page.locator('#structureReplaceCancel').click()
                    page.locator('#keyboardHelp').scroll_into_view_if_needed();page.screenshot(path=str(folder/f'public_keyboard_{width}.png'));keypress(page,'a','canvas');wait_value(page,'!taxonomyDiagnostics().opening&&!taxonomyDiagnostics().saving')
                    page.locator('#close').click();require(page.evaluate('document.documentElement.scrollWidth<=innerWidth'),'Narrow overflow')
                    viewports.append(dict(width=width,default_visible=default,all_history=len(props),login_images_and_preview=True,A_no_submit=True,CtrlS_help_readonly_verified=True))
                except Exception:
                    import traceback
                    n=1
                    while (folder/f'public_failure_{n}.json').exists():n+=1
                    page.screenshot(path=str(folder/f'public_failure_{n}.png'));write(folder/f'public_failure_{n}.json',dict(width=width,traceback=traceback.format_exc(),page_errors=errors));raise
                finally:context.close()
            results[mode]=dict(state='round7_ptunnel_authenticated_public_readonly_passed',public_url=url,targets=len(props),sampled_classes=classes,viewports=viewports,task_manifest_sha256=digest(s['root']/'manifest.json'),overlay_manifest_sha256=digest(folder/'manifest.json'),production_annotation_POSTs=0)
        browser.close()
    require(not errors and not blocked and sources_current(),'Public page/forbidden write/source error')
    for mode,s in REVIEW_SETS.items():
        folder=RELEASE/mode;snapshot_db(s['reviews']/'mask_reviews.sqlite3',folder/'after_public.sqlite3');bm,be,_=state(folder/'before_public.sqlite3');am,ae,ar=state(folder/'after_public.sqlite3')
        require(bm==am and ae[:len(be)]==be and ar=={k:(rev,raw) for _,k,rev,raw in ae},'Production history altered')
        write(s['managed']/'round7_public_verification.json',dict(results[mode],events_before=len(be),events_after=len(ae),raw_history_prefix_preserved=True,page_errors=errors,blocked_writes=blocked,production_decision_POSTs=0,real_MacOS_iPhone_Safari_not_tested=True,implementation_sha256=digest(Path(__file__))))
    print(dict(state='round7_actual_ptunnel_readonly_passed',services={m:dict(url=v['public_url'],targets=v['targets']) for m,v in results.items()},production_annotation_POSTs=0))


if __name__=='__main__':verify()
