"""Public byte check plus local production A/D; never save an annotation."""
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,require
from pallet.mask_taxonomy_data import REQUESTS,REVIEWS,MANAGED,sources_current
from pallet.mask_taxonomy_keyboard_ui import CHECKS,SPEC,active_configuration
from pallet.mask_template_refined import readonly
from review_http_pool import ReadOnlyHTTP
from check_mask_under50_ui import wait_value


def events():
    with closing(readonly(REVIEWS/'mask_reviews.sqlite3')) as db:return list(db.execute('SELECT id,target_key,revision,payload FROM events ORDER BY id'))


def check():
    require(not (CHECKS/'HANDOFF.json').exists(),'Preserve existing keyboard handoff')
    active_configuration();before=events();runtime=read(MANAGED/'public_access.json');spec=read(SPEC)
    base=runtime['public_url'];checked=[]
    with ReadOnlyHTTP(base) as client:
        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'],'Wrong live keyboard UI bytes: '+name);checked.append(name)
        health=client.get('/healthz').json();require(health['editing_enabled'] and health['targets']==1831,'Wrong live task service')
    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
    secret=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip();posts=[];errors=[]
    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'])
        context=browser.new_context(viewport=dict(width=1400,height=1000));page=context.new_page()
        page.on('pageerror',lambda error:errors.append(str(error)));page.on('request',lambda req:posts.append(req.url) if req.method=='POST' and '/api/review/annotations/' in req.url else None)
        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');require(page.locator('#cards button').count()>=2,'Need2 real items for readonly public navigation')
            page.locator('#cards button').first.click();wait_value(page,'taxonomyDiagnostics().detail&&!taxonomyDiagnostics().opening');first=page.evaluate('taxonomyDiagnostics()')
            page.locator('#canvas').focus();page.keyboard.press('d');wait_value(page,'!taxonomyDiagnostics().opening&&taxonomyDiagnostics().navigationIndex===1');second=page.evaluate('taxonomyDiagnostics()')
            require(second['detail']!=first['detail'],'Public D did not switch image')
            page.keyboard.press('a');wait_value(page,'!taxonomyDiagnostics().opening&&taxonomyDiagnostics().navigationIndex===0');back=page.evaluate('taxonomyDiagnostics()')
            require(back['detail']==first['detail'] and back['points']==first['points'] and back['class_id']==first['class_id'] and back['revision']==first['revision'],'Public A did not restore same item/state')
            require('存草稿' in page.locator('#keyboardHelp').inner_text(),'Live shortcut help missing')
            page.locator('.target-navigation').screenshot(path=str(CHECKS/'public_keyboard_bar.png'))
        finally:context.close();browser.close()
    after=events();require(after[:len(before)]==before,'Existing real human history was changed')
    require(not posts and not errors and sources_current(),'Public test attempted annotation POST, browser failed or source changed')
    reload=read(CHECKS/'app_reload.json')
    value=dict(state='keyboard_shortcuts_live_same_URL_public_readonly_verified',public_url=base,local_url=runtime['local_url'],
        public_UI_assets_verified=checked,actual_local_production_A_D_roundtrip=True,public_annotation_POSTs=0,
        actual_public_browser_navigation=False,headless_public_browser_limitation='ERR_INVALID_AUTH_CREDENTIALS from browser network path; public HTTP asset hashes verified separately',
        original_review_events_at_reload=reload['original_review_events_before'],review_events_before_public_check=len(before),review_events_after_public_check=len(after),
        original_raw_event_prefix_preserved=True,same_namespace_and_draft_keys=True,
        original_task_manifest_sha256=digest(REQUESTS/'manifest.json'),keyboard_ui_sha256=digest(SPEC),
        acceptance_sha256=digest(CHECKS/'ui_acceptance.json'),CPU_regressions=242,
        regression_receipt_sha256=digest(CHECKS/'regressions.xml'),old3410_and3411_and3406_to3409_preserved=True,
        real_MacOS_and_iPhone_Safari_tested=False,page_errors=errors,code_sha256=digest(__file__))
    write(CHECKS/'HANDOFF.json',value);print({k:value[k] for k in ('state','public_url','actual_local_production_A_D_roundtrip','public_annotation_POSTs','review_events_after_public_check')},flush=True)


if __name__=='__main__':check()
