"""Read-only production login, full preview and GUI; never applies annotations."""
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,require,jsonl
from pallet.pallet_description_terms import RELEASE
from pallet.pallet_description_round5_release import REVIEW_SETS
from pallet.mask_class_note_integration import snapshot_db
from reload_mask_taxonomy_keyboard_ui import state
from check_mask_under50_ui import wait_value
from check_mask_taxonomy_keyboard_ui import keypress


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();results=[];errors=[];blocked=[]
    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'])
        for mode,s in REVIEW_SETS.items():
            folder=RELEASE/mode;url=read(s['managed']/'public_access.json')['public_url'];props=jsonl(s['root']/'proposals.jsonl');first=props[0]
            # Exact resource bytes and complete current revision sequence over ptunnel.
            with requests.Session() as http:
                http.headers.update({'X-Review-Request':'1','Origin':url})
                response=http.post(url+'/api/review/login',json=dict(key=key),timeout=60);require(response.status_code==200,'Public login failed')
                for name,h in read(folder/'manifest.json')['assets'].items():
                    response=http.get(url+'/'+name,timeout=60);require(response.status_code==200 and hashlib.sha256(response.content).hexdigest()==h,'Public overlay bytes differ')
                summary=http.get(url+'/api/review/summary',timeout=60).json()['reviews'];detail=http.get(url+'/api/review/targets/'+first['target_key'],timeout=60).json()
                body=dict(binding=detail['binding'],source_key=first['target_key'],source_binding=detail['source_binding'],batch_id='ab'*16,
                    items=[[p['target_key'],summary.get(p['target_key'],{}).get('revision',0)] for p in props],scope=dict(class_filter='',state_filter='all'),operation='delete',terms_text='SYNTHETIC READ ONLY PREVIEW NEVER APPLY',reviewer='复核人1')
                response=http.post(url+'/api/review/structure-terms-batch/preview',json=body,timeout=90)
                # Concurrent real annotation writes are legitimate, not a reason to apply a test.
                require(response.status_code in (200,409),'Public preview route failed')
                if response.status_code==200:
                    preview=response.json();require(preview['count']==len(props) and preview['changed_count']==0,'Public full preview incorrect')
                full_preview=dict(status=response.status_code,targets=len(props),apply_called=False)
            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):
                    request=route.request;allowed=request.method in ('GET','HEAD') or request.method=='POST' and request.url in (url+'/api/review/login',url+'/api/review/structure-terms-batch/preview')
                    if not allowed:blocked.append(dict(method=request.method,url=request.url));route.abort()
                    else:route.continue_()
                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')
                    # Human reclassification can move the initial proposal's
                    # class out of its original filter; use the live all-target
                    # sequence rather than assuming two current cards in it.
                    page.locator('#stateFilter').select_option('all');page.locator('#classFilter').select_option('');page.locator('#cards button').nth(1).click()
                    wait_value(page,'!!taxonomyDiagnostics().detail&&!taxonomyDiagnostics().opening')
                    page.locator('#structureTermsInput').fill('SYNTHETIC READ ONLY PREVIEW NEVER APPLY');page.locator('#structureTermsAdd').click();page.locator('#structureTermsPreview').wait_for(state='visible',timeout=60000)
                    require('实际变更' in page.locator('#structureTermsScope').inner_text(),'Public add preview missing');page.locator('#structureTermsCancel').click()
                    page.locator('#structureTermsDelete').click();page.locator('#structureTermsPreview').wait_for(state='visible',timeout=60000)
                    require('实际变更0项' in page.locator('#structureTermsScope').inner_text(),'Public delete no-op preview incorrect')
                    page.locator('#structureTermsPreview').scroll_into_view_if_needed();page.screenshot(path=str(folder/f'public_terms_{width}.png'));page.locator('#structureTermsCancel').click()
                    keypress(page,'a','canvas');wait_value(page,'!taxonomyDiagnostics().opening&&!taxonomyDiagnostics().saving')
                    require(page.locator('#reviewer').input_value()=='复核人1' and page.evaluate('document.documentElement.scrollWidth<=innerWidth'),'Public reviewer/viewport changed')
                    results.append(dict(mode=mode,width=width,url=url,add_delete_preview=True,A_only=True,full_preview=full_preview))
                finally:context.close()
        browser.close()
    require(not blocked and not errors,'Production GUI attempted a forbidden write or page error')
    for mode,s in REVIEW_SETS.items():
        folder=RELEASE/mode;snapshot_db(s['reviews']/'mask_reviews.sqlite3',folder/'after_public.sqlite3')
        m,e,_=state(folder/'before_reload.sqlite3');am,ae,ar=state(folder/'after_public.sqlite3')
        require(m==am and ae[:len(e)]==e and ar=={k:(rev,raw) for _,k,rev,raw in ae},'Production history prefix changed')
        write(folder/'production_history_check.json',dict(raw_history_prefix_preserved=True,events_before=len(e),events_after=len(ae),saved_reviews=len(ar),concurrent_real_user_events_preserved=len(ae)-len(e),production_annotation_POSTs=0))
    write(RELEASE/'public_verification.json',dict(state='passed_ptunnel_terms_desktop390_readonly',viewports=results,page_errors=errors,blocked_writes=blocked,production_annotation_POSTs=0,
        simulated_apply_or_single_save_never_called=True,real_iPhone_MacOS_Safari_not_tested=True,implementation_sha256=digest(Path(__file__))))
    print(dict(state='public_terms_readonly_passed',viewports=len(results),production_annotation_POSTs=0))


if __name__=='__main__':verify()
