"""Read-only public mask-proposal smoke test, including cancelled adoption."""
import json
import os
from pathlib import Path
import sys
import time

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


def main():
    out=PROJECT/'outputs/pallet_pose_review_validation_v14';out.mkdir(parents=True,exist_ok=True)
    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
    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()
    proposals=[json.loads(s) for s in (PROJECT/'outputs/pallet_mask_template_bulk_v2/proposals.jsonl').read_text().splitlines()]
    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(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'])
        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 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)))
            key=proposals[0]['target_key']
            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"')
            data=page.evaluate('async key=>(await fetch("/api/targets/"+key)).json()',key)
            queue=page.evaluate('async ()=>(await fetch("/api/queue?state=mask_proposal")).json()')
            assert data['mask_suggestion'] and key in queue['keys'] and len(queue['keys'])<=52
            assert len(queue['keys'])>0
            before=page.evaluate('poseReviewDiagnostics()');assert before['uiVersion']==UI_VERSION
            assert not before['dirty'] and page.locator('#maskSuggestionBanner').is_visible()
            assert before['polygon']==(data['review']['polygon'] if data['review'] else data['initial_polygon'])
            assert before['polygon']!=data['mask_suggestion']['polygon']
            assert page.locator('#applyMaskSuggestion').is_enabled()
            page.once('dialog',lambda dialog:dialog.dismiss());page.locator('#applyMaskSuggestion').click()
            after=page.evaluate('poseReviewDiagnostics()');assert after['polygon']==before['polygon'] and after['ruler']==before['ruler'] and not after['dirty']
            # Selection itself applies this filter; the redundant button is
            # intentionally hidden on mobile, so do not click it there.
            page.locator('#queueState').select_option('mask_proposal')
            wait(page,'!poseReviewDiagnostics().loading && poseReviewDiagnostics().queueTotal==='+str(len(queue['keys'])))
            assert page.evaluate('poseReviewDiagnostics().queueTotal')==len(queue['keys'])
            assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
            page.screenshot(path=str(out/f'public_{mode}_mask_suggestions.png'))
            after_data=page.evaluate('async key=>(await fetch("/api/targets/"+key)).json()',key)
            assert after_data['review']==data['review']
            checks.append(dict(mode=mode,target_key=key,available_suggestions=len(queue['keys']),
                pending_vertex_count=data['mask_suggestion']['vertex_count'],original_review_unchanged=True,
                cancel_adoption_no_edit=True,filter_verified=True,no_overflow=True))
            context.close()
        browser.close()
    assert not blocked and not errors
    result=dict(state='passed',ui_version=UI_VERSION,public_url=access['public_url'],checks=checks,
        annotation_mutation_attempts=blocked,page_errors=errors,production_annotation_writes=0,real_iPhone_Safari_tested=False)
    (out/'masks_public_browser.json').write_bytes(canonical(result)+b'\n');print(json.dumps(result),flush=True)


if __name__=='__main__':main()
