"""Actual public login/image/A-only navigation; production annotation POST blocked."""
from pathlib import Path
import os
import sys

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.mask_model_training_data import read,write,require,jsonl
from pallet.pallet_review_ptunnel import MIGRATION
from pallet.pallet_description_round5_release import REVIEW_SETS
from check_mask_taxonomy_complete_ui import idle
from check_mask_taxonomy_keyboard_ui import keypress,diag
from check_mask_under50_ui import wait_value


def check():
    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','--disable-features=VizDisplayCompositor'])
        for mode,s in REVIEW_SETS.items():
            url=read(s['managed']/'public_access.json')['public_url'];queue=jsonl(s['root']/'proposals.jsonl')
            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
                    if request.method not in ('GET','HEAD') and not (request.method=='POST' and request.url==url+'/api/review/login'):
                        blocked.append(dict(method=request.method,url=request.url));route.abort();return
                    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')
                    page.locator('#stateFilter').select_option('all');page.locator('#cards button').nth(1).click();idle(page,queue[1]['target_key'])
                    state=diag(page);require(state['points']==len(queue[1]['polygon']),'Wrong public image/target geometry')
                    keypress(page,'a','canvas');idle(page,queue[0]['target_key'])
                    require(page.locator('#structureBatch').count()==1 and page.locator('#structureAttributesBatch').count()==1,'Batch controls missing')
                    require(page.locator('#reviewer').input_value()=='复核人1','Reviewer policy changed')
                    page.locator('#canvas').screenshot(path=str(MIGRATION/mode/f'public_ptunnel_canvas_{width}.png'))
                    require(page.evaluate('document.documentElement.scrollWidth<=innerWidth'),'Narrow page overflow')
                    cookie=next(c for c in context.cookies() if c['name']==f'pallet_joint_description_{mode}')
                    results.append(dict(mode=mode,width=width,public_url=url,login_passed=True,public_image_opened=True,A_no_submit=True,
                        namespace_draft_key_preserved=True,HttpOnly=cookie['httpOnly'],secure_cookie=cookie['secure'],sameSite=cookie['sameSite']))
                finally:context.close()
        browser.close()
    require(not blocked and not errors,'Public GUI attempted forbidden mutation or JavaScript error')
    write(MIGRATION/'public_browser_verification.json',dict(state='ptunnel_actual_desktop390_login_image_and_A_only_passed',viewports=results,
        page_errors=errors,production_annotation_POSTs=0,save_buttons_not_clicked=True,actual_MacOS_iPhone_Safari_not_tested=True))
    print(dict(state='public_GUI_passed',viewports=len(results),production_annotation_POSTs=0))


if __name__=='__main__':check()
