"""Production read-only verification: NEVER press D/next/save with the v5 UI."""
import hashlib
import os
from pathlib import Path
import statistics
import sys
import time

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.mask_taxonomy_data import REQUESTS,REVIEWS,MANAGED,sources_current
from pallet.mask_taxonomy_complete_ui import SPEC,CHECKS,SCHEMA,active_configuration
from reload_mask_taxonomy_keyboard_ui import state
from review_http_pool import ReadOnlyHTTP
from check_mask_taxonomy_complete_ui import idle
from check_mask_under50_ui import wait_value


def check(out):
    require(not out.exists(),'Preserve previous complete-next public verification')
    active_configuration();metadata,before,_=state(REVIEWS/'mask_reviews.sqlite3');runtime=read(MANAGED/'public_access.json');spec=read(SPEC)
    secret=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip();checked={};timings=[]
    props=jsonl(REQUESTS/'proposals.jsonl');selected=[next(p for p in props if p['class_id']==c) for c in (1,11,12,9,4)]
    for label,base in [('local',runtime['local_url']),('public',runtime['public_url'])]:
        with ReadOnlyHTTP(base,attempts=2) as client:
            health=client.get('/healthz').json();require(health.get('completion_navigation_version')==SCHEMA and health['targets']==1831,'Wrong production completion UI version')
            checked[label]=[]
            for name,item in spec['assets'].items():
                path='/report_zh.html' if name=='page.html' else '/'+name
                require(hashlib.sha256(client.get(path).content).hexdigest()==item['sha256'],'Production complete-next asset differs: '+name);checked[label].append(name)
            client.login(secret,gallery=True)
            for p in selected:
                t=time.perf_counter();value=client.get('/api/review/targets/'+p['target_key']).json();elapsed=(time.perf_counter()-t)*1000
                require(value['source_current'],'Sources changed during live verification');timings.append(dict(origin=label,class_id=p['class_id'],detail_ms=elapsed))
    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
    attempted_posts=[];errors=[];navigations=[]
    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 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 block_annotation(route):
                if route.request.method=='POST':
                    attempted_posts.append(route.request.url);route.fulfill(status=405,content_type='application/json',body='{"error":"Production verification is read-only"}')
                else:route.continue_()
            context.route('**/api/review/annotations/**',block_annotation)
            page=context.new_page();page.on('pageerror',lambda e:errors.append(str(e)))
            try:
                page.goto(runtime['local_url'],wait_until='domcontentloaded');page.locator('#key').fill(secret);page.locator('#loginButton').click();wait_value(page,'window.taxonomyDiagnostics&&taxonomyDiagnostics().loaded')
                page.locator('#classFilter').select_option('1');page.locator('#cards button').last.click();idle(page)
                require('完成最后一条' in page.locator('#nextTarget').inner_text() and 'D 保存当前轮廓并完成复核' in page.locator('#keyboardHelp').inner_text(),'Live completion labels missing')
                old=page.evaluate('taxonomyDiagnostics()');page.locator('#canvas').focus();page.keyboard.press('a');wait_value(page,'!taxonomyDiagnostics().opening&&taxonomyDiagnostics().navigationIndex==='+str(old['navigationIndex']-1));idle(page)
                new=page.evaluate('taxonomyDiagnostics()');require(new['nextAction']=='save_correct_then_advance' and '完成并下一条' in page.locator('#nextTarget').inner_text(),'Live navigation semantics missing')
                navigations.append(dict(width=width,previous_A_only=True,next_or_save_never_invoked=True,index_before=old['navigationIndex'],index_after=new['navigationIndex']))
                page.locator('.target-navigation').screenshot(path=str(CHECKS/f'live_complete_bar_{width}.png'))
            finally:context.close()
        browser.close()
    new_metadata,after,_=state(REVIEWS/'mask_reviews.sqlite3');require(new_metadata==metadata and after[:len(before)]==before,'Original production raw event prefix changed')
    require(not attempted_posts and not errors and sources_current(),'Production verification attempted a save, browser error, or source change')
    write(out,dict(state='complete_next_live_readonly_verified_same_URL',public_url=runtime['public_url'],local_url=runtime['local_url'],
        assets_verified=checked,HTTP_samples=timings,detail_median_ms={label:statistics.median(r['detail_ms'] for r in timings if r['origin']==label) for label in ('local','public')},
        viewports=navigations,production_annotation_POSTs=0,annotation_POST_route_blocked_as_safety=True,
        browser_cache_policy='routing_disables_cache_no_navigation_performance_claim',actual_public_GUI_verified=False,real_MacOS_or_iPhone_Safari_tested=False,
        page_errors=errors,real_events_before=len(before),real_events_after=len(after),original_raw_prefix_preserved=True,
        manifest_sha256=digest(REQUESTS/'manifest.json'),ui_spec_sha256=digest(SPEC),acceptance_sha256=digest(CHECKS/'acceptance.json'),code_sha256=digest(__file__)))
    print(dict(state='complete_next_live_readonly_verified_same_URL',public_url=runtime['public_url'],production_annotation_POSTs=0,real_events_after=len(after)),flush=True)


if __name__=='__main__':
    import argparse
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--output',type=Path,default=CHECKS/'HANDOFF.json');a=p.parse_args();check(a.output.resolve())
