"""Public mobile smoke check: open/cancel deletion; block all annotation mutations."""
from __future__ import annotations

import argparse
import json
import os
from pathlib import Path
import sys
import time
from urllib.parse import quote

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


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output',type=Path,default=PROJECT/'outputs/pallet_pose_review_validation_v8')
    parser.add_argument('--check-vim-help',action='store_true')
    parser.add_argument('--check-alt-vim-help',action='store_true')
    parser.add_argument('--check-alt-zoom',action='store_true')
    parser.add_argument('--check-metres',action='store_true')
    args=parser.parse_args()
    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=args.output;out.mkdir(parents=True,exist_ok=True)
    dataset=Path(json.loads((PROJECT/'configs/active_formal_dataset.json').read_text())['dataset'])
    row=next(json.loads(line) for line in (dataset/'annotations/frames.jsonl').read_text().splitlines() if len(json.loads(line)['boxes'])>=2)
    key=target_key(row['frame_id'],0)
    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()
    blocked=[];errors=[]
    def wait(page,condition):
        deadline=time.monotonic()+60
        while time.monotonic()<deadline:
            if page.evaluate(condition):return
            time.sleep(.08)
        raise AssertionError('Public UI timeout: '+condition)
    with sync_playwright() as p:
        browser=p.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=390,height=844),is_mobile=True,has_touch=True,device_scale_factor=2)
        def deny(route):
            blocked.append(route.request.url);route.fulfill(status=403,content_type='application/json',body='{"error":"read-only deployment test"}')
        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='+quote(key),wait_until='domcontentloaded',timeout=60000)
        page.locator('#accessKey').fill(password);page.locator('#loginForm button').click()
        wait(page,'window.poseReviewDiagnostics && !poseReviewDiagnostics().loading && poseReviewDiagnostics().imageStatus==="ready"')
        diag=page.evaluate('poseReviewDiagnostics()');assert diag['uiVersion']==UI_VERSION and not diag['dirty']
        assert len(diag['frameObjects'])>=2 and not diag['deleted']
        assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
        page.locator('#deleteObject').click();assert page.locator('#objectDialog').is_visible()
        assert '仅删除' in page.locator('#objectScope').inner_text()
        assert not page.locator('#objectConfirm').is_checked()
        page.screenshot(path=str(out/'public-mobile-delete-confirm.png'))
        page.locator('#closeObjectDialog').click();assert not page.locator('#objectDialog').is_visible()
        assert page.evaluate('poseReviewDiagnostics().target')==diag['target'] and not page.evaluate('poseReviewDiagnostics().dirty')
        page.screenshot(path=str(out/'public-mobile-multibox.png'))
        if args.check_vim_help or args.check_alt_vim_help or args.check_alt_zoom:
            before=page.evaluate('poseReviewDiagnostics()')
            page.keyboard.press('Shift+/');assert page.locator('#shortcuts').is_visible()
            help_text=page.locator('#shortcuts').inner_text()
            assert 'H / J / K / L' in help_text and 'H不再打开帮助' in help_text
            if args.check_alt_vim_help:
                assert 'Alt+H / Alt+L' in help_text and 'Alt+J / Alt+K' in help_text
            if args.check_alt_zoom:assert 'Alt+A / Alt+D' in help_text
            page.screenshot(path=str(out/'public-mobile-vim-help.png'))
            page.locator('#closeShortcuts').click()
            assert page.evaluate('poseReviewDiagnostics().ruler')==before['ruler']
        if args.check_alt_zoom:
            page.evaluate('document.activeElement.blur()');page.keyboard.press('2')
            before=page.evaluate('poseReviewDiagnostics()')
            page.keyboard.press('Alt+a');after=page.evaluate('poseReviewDiagnostics()')
            assert abs(after['view']['span']-before['view']['span']*1.3)<1e-10
            page.keyboard.press('Alt+d');after=page.evaluate('poseReviewDiagnostics()')
            assert abs(after['view']['span']-before['view']['span'])<1e-10
            assert after['target']==before['target'] and after['ruler']==before['ruler'] and not after['dirty']
            assert after['revision']==before['revision']
            page.screenshot(path=str(out/'public-mobile-alt-zoom.png'))
        if args.check_metres:
            # Latest is read before navigation. Unit-only revisions must not
            # replace the most recent genuinely human-saved target.
            latest=page.evaluate('''async()=>{const r=await fetch('/api/locate?mode=latest');
                if(!r.ok)throw Error('Latest lookup failed');return await r.json();}''')
            latest_key=latest['matches'][0]['target_key']
            page.locator('#jumpButton').click();page.locator('#jumpMode').select_option('image')
            page.locator('#jumpValue').fill(latest_key);page.locator('#jumpSubmit').click()
            wait(page,'!document.querySelector("#jumpDialog").open && !poseReviewDiagnostics().loading')
            current=page.evaluate('poseReviewDiagnostics()')
            assert current['target']==latest_key and current['unit']=='m' and current['positionStep']==.001
            assert current['sensor']['scale_to_m'] is not None and current['unitPolicy']
            assert not current['dirty'] and current['geometryToken']
            page.locator('#settingsButton').click()
            assert page.locator('#displayUnit').input_value()=='m' and page.locator('#displayUnit option').count()==1
            assert page.locator('#rulerW').get_attribute('step')=='0.001'
            page.screenshot(path=str(out/'public-mobile-latest-metres.png'))
            page.locator('#closeSettings').click()
        assert not blocked and not errors
        stats=page.locator('#progress').inner_text();context.close();browser.close()
    atomic_json(out/'public_browser.json',dict(state='passed',ui_version=UI_VERSION,
        public_url=access['public_url'],target=key,frame_objects=len(diag['frameObjects']),
        mobile_size=[390,844],progress=stats,open_and_cancel_confirmation_verified=True,
        vim_help_verified=args.check_vim_help,
        alt_vim_help_verified=args.check_alt_vim_help,
        alt_zoom_verified=args.check_alt_zoom,
        metres_and_latest_verified=args.check_metres,
        annotation_delete_restore_requests=blocked,page_errors=errors,production_annotation_writes=0,
        real_iPhone_Safari_tested=False))
    print(json.dumps(dict(state='passed',public_read_only=True,frame_objects=len(diag['frameObjects']))),flush=True)


if __name__=='__main__':main()
