"""Public axis rollout verification; annotation writes are blocked in browser."""
import json
import os
from pathlib import Path
import sys
import time

import numpy as np

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.pose_review import UI_VERSION
from pallet.pose_refinement import atomic_json


def main():
    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
    out=PROJECT/'outputs/pallet_pose_review_validation_v13';out.mkdir(parents=True,exist_ok=True)
    access=json.loads((PROJECT/'outputs/pallet_pose_review_managed_v1/public_access.json').read_text())
    password=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    key='16ec2d2178c392642b5172b1';checks=[];blocked=[];errors=[]
    def wait(page,condition):
        deadline=time.monotonic()+90
        while time.monotonic()<deadline:
            if page.evaluate(condition):return
            time.sleep(.1)
        raise AssertionError('Public axes timeout '+condition)
    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 mobile in (False,True):
            mode='mobile' if mobile else 'desktop'
            context=browser.new_context(viewport=dict(width=390 if mobile else 1400,height=844 if mobile else 1000),is_mobile=mobile,has_touch=mobile)
            def deny(route):
                blocked.append(route.request.url);route.fulfill(status=403,content_type='application/json',body='{"error":"read-only axis acceptance"}')
            for pattern in ('**/api/annotations/**','**/api/delete-object/**','**/api/restore-object/**'):context.route(pattern,deny)
            page=context.new_page();page.on('pageerror',lambda e:errors.append(str(e)))
            page.goto(access['public_url']+'/?target='+key,wait_until='domcontentloaded',timeout=60000)
            page.locator('#accessKey').fill(password);page.locator('#loginForm button').click()
            wait(page,'window.poseReviewDiagnostics && !poseReviewDiagnostics().loading && !!poseReviewDiagnostics().geometryToken && poseReviewDiagnostics().imageStatus==="ready"')
            d=page.evaluate('poseReviewDiagnostics()');assert d['uiVersion']==UI_VERSION and d['target']==key
            assert d['sensor']['forward_axis']==2 and d['sensor']['up_axis']==1
            assert d['sensor']['forward_sign']==d['sensor']['up_sign']==1 and d['sensor']['scale_to_m']==.001
            assert d['axesPolicy'] and d['positionStep']==.001 and d['unit']=='m' and not d['dirty']
            b=np.asarray(d['ruler']['basis']);np.testing.assert_allclose(b[:,2],[0,1,0],atol=1e-8)
            assert b[0,0]<-.9 and b[2,1]>.9 and d['ruler']['half_width']>.3
            assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
            page.evaluate('document.activeElement.blur()');page.keyboard.press('2')
            page.screenshot(path=str(out/('public-'+mode+'-corrected-cloud.png')))
            page.locator('#settingsButton').click()
            assert 'Y 高度未标注' in page.locator('#poseReadout').inner_text()
            assert 'θ_WP' in page.locator('#poseReadout').inner_text()
            assert page.locator('#forwardAxis').input_value()=='2' and page.locator('#upAxis').input_value()=='1'
            assert page.locator('#forwardAxis').is_disabled() and page.locator('#upAxis').is_disabled()
            page.screenshot(path=str(out/('public-'+mode+'-corrected-controls.png')));page.locator('#closeSettings').click()
            page.evaluate('document.activeElement.blur()');page.keyboard.press('Alt+a');page.keyboard.press('Alt+d')
            after=page.evaluate('poseReviewDiagnostics()');assert after['ruler']==d['ruler'] and not after['dirty']
            checks.append(dict(mode=mode,axes_and_metres_verified=True,source_height_not_reported=True,
                corrected_basis=d['ruler']['basis'],total_width_m=2*d['ruler']['half_width'],revision=d['revision']))
            context.close()
        browser.close()
    assert not blocked and not errors
    atomic_json(out/'axes_public_browser.json',dict(state='passed',ui_version=UI_VERSION,public_url=access['public_url'],
        target=key,checks=checks,annotation_mutations_attempted=blocked,page_errors=errors,
        production_annotation_writes=0,real_iPhone_Safari_tested=False))
    print(json.dumps(dict(state='passed',checks=len(checks),public_read_only=True)))


if __name__=='__main__':main()
