"""Read-only desktop/mobile checks of review-only navigation and protected new tasks."""
import json
import os
from pathlib import Path
import sys
import time
from urllib.parse import urlsplit,unquote

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.pose_review_geometry import canonical


def main():
    root=PROJECT/'outputs/pallet_mask_remaining_round2_v1'
    tasksroot=PROJECT/json.loads((PROJECT/'configs/active_mask_template_requests.json').read_text())['directory']
    out=PROJECT/'outputs/pallet_mask_remaining_round2_deployment_v1';result=out/'task_and_original_review_ui_acceptance.json'
    if result.exists():raise ValueError('Preserve completed public UI evidence')
    manifest=json.loads((root/'manifest.json').read_text());assert manifest['publication_version']==12
    manual=[json.loads(s) for s in (root/'manual_proposals.jsonl').read_text().splitlines()]
    originals=[p for p in manual if p.get('original_rectangle_review_only')];assert len(originals)==3
    tasks=[json.loads(s) for s in (tasksroot/'requests.jsonl').read_text().splitlines()]
    work=json.loads((tasksroot/'manifest.json').read_text());classes=sorted({t['class_id'] for t in tasks})
    assert classes==[4,5,7,14,22] and work['request_count']==len(tasks)
    base=json.loads((PROJECT/'outputs/pallet_mask_gallery_managed_v1/public_access.json').read_text())['public_url']
    password=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    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
    launch={};proxy_url=os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy')
    if proxy_url:
        proxy=urlsplit(proxy_url);launch['proxy']=dict(server=f'{proxy.scheme}://{proxy.hostname}:{proxy.port}',bypass='127.0.0.1,localhost')
        if proxy.username is not None:launch['proxy']['username']=unquote(proxy.username)
        if proxy.password is not None:launch['proxy']['password']=unquote(proxy.password)
    checks=[];writes=[];errors=[]
    def wait(page,condition):
        end=time.monotonic()+90
        while time.monotonic()<end:
            if page.evaluate(condition):return
            time.sleep(.1)
        raise AssertionError(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'],**launch)
        for width in (1400,390):
            context=browser.new_context(viewport=dict(width=width,height=1000),is_mobile=width==390,has_touch=width==390)
            page=context.new_page();page.on('pageerror',lambda error:errors.append(str(error)))
            def deny(route):
                writes.append(route.request.url);route.fulfill(status=403,content_type='application/json',body='{"error":"read-only acceptance"}')
            for pattern in ('**/api/annotations/**','**/api/delete-object/**','**/api/restore-object/**','**/api/review/annotations/**'):
                context.route(pattern,deny)
            page.goto(base+'/?revision=12',wait_until='domcontentloaded',timeout=90000)
            wait(page,f'window.maskGalleryDiagnostics && document.querySelectorAll(".mg-edit-button[data-key]").length==={manifest["proposals"]}')
            page.locator('#only-new').uncheck()
            for i,proposal in enumerate(originals):
                key=proposal['target_key'];page.locator(f'.mg-edit-button[data-key="{key}"]').click()
                if i==0:
                    wait(page,'document.querySelector("#mgLogin").open');page.locator('#mgAccessKey').fill(password);page.locator('#mgLoginSubmit').click()
                wait(page,f'maskGalleryDiagnostics().target==="{key}" && maskGalleryDiagnostics().imageStatus==="ready" && !maskGalleryDiagnostics().loading')
                before=page.evaluate('async key=>(await fetch("/api/review/targets/"+key)).json()',key)
                diagnostic=page.evaluate('maskGalleryDiagnostics()');assert not diagnostic['dirty']
                if before['review'] is None:
                    assert diagnostic['polygon']==proposal['polygon'] and '已复核保留原框' in page.locator('#mgState').inner_text()
                    assert page.locator('#mgHistory button').count()==0
                assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
                page.screenshot(path=str(out/f'review_only_{key}_{width}.png'))
                page.locator('#mgNext').click()
                wait(page,f'maskGalleryDiagnostics().target!=="{key}" && maskGalleryDiagnostics().imageStatus==="ready" && !maskGalleryDiagnostics().loading')
                assert not page.evaluate('maskGalleryDiagnostics().dirty');page.locator('#mgClose').click()
                after=page.evaluate('async key=>(await fetch("/api/review/targets/"+key)).json()',key)
                assert after['review']==before['review'] and after['history']==before['history']
                checks.append(dict(width=width,original_review_target=key,next_without_fake_save=True,no_fake_gallery_history=True))
            page.goto(base+'/template-requests/?batch=remaining-round2-v1',wait_until='domcontentloaded',timeout=90000)
            page.evaluate('document.fonts.ready')
            assert '已独立核验' in page.locator('h1').inner_text() and '尚未激活' not in page.locator('h1').inner_text()
            assert page.locator('article').count()==len(tasks) and page.evaluate('document.documentElement.scrollWidth<=innerWidth')
            for cls in classes:
                page.locator('#request-filter').select_option(str(cls));assert page.locator('article:visible').count()==sum(t['class_id']==cls for t in tasks)
            page.locator('#request-filter').select_option('');page.screenshot(path=str(out/f'published_tasks_{width}.png'))
            for i,cls in enumerate((4,14,22)):
                task=next(t for t in tasks if t['class_id']==cls);key=task['target_key']
                page.goto(task['pose_annotation_url'],wait_until='domcontentloaded',timeout=90000)
                if i==0:page.locator('#accessKey').fill(password);page.locator('#loginForm button').click()
                wait(page,f'window.poseReviewDiagnostics && poseReviewDiagnostics().target==="{key}" && !poseReviewDiagnostics().loading && poseReviewDiagnostics().imageStatus==="ready"')
                diagnostic=page.evaluate('poseReviewDiagnostics()');assert not diagnostic['dirty']
                detail=page.evaluate('async key=>(await fetch("/api/targets/"+key)).json()',key)
                assert detail['mask_suggestion'] is None
                if task['existing_pose_record']:
                    assert detail['review']==task['existing_pose_current_payload'] and diagnostic['polygon']==detail['review']['polygon']
                else:assert detail['review'] is None
                checks.append(dict(width=width,class_id=cls,target_key=key,existing_pose_record=task['existing_pose_record'],
                    correct_target_deeplink=True,no_automatic_edit=True))
            context.close()
        browser.close()
    assert not writes and not errors
    value=dict(state='passed',task_count=len(tasks),classes=classes,all_task_class_filters_correct=True,
        online_title_matches_independent_seal=True,three_new_original_box_reviews_not_fake_edits=True,
        checks=checks,production_annotation_writes=0,mutation_attempts=writes,page_errors=errors,real_iPhone_Safari_tested=False)
    result.write_bytes(canonical(value)+b'\n');print(json.dumps(value),flush=True)


if __name__=='__main__':main()
