"""Read-only actual public UI acceptance of already drawn new-image tasks."""
from collections import Counter
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
from scripts.build_mask_template_requests import database_fingerprint


def main():
    import argparse
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output',type=Path,default=PROJECT/'outputs/pallet_mask_remaining_round3_deployment_v1')
    parser.add_argument('--batch',default='preannotated-v1');args=parser.parse_args();out=args.output.resolve()
    if not out.is_relative_to(PROJECT/'outputs'):raise ValueError('Expected an acceptance output directory')
    result=out/'preannotation_public_ui_acceptance.json'
    if result.exists():raise ValueError('Preserve completed public preannotation check')
    taskconfig=json.loads((PROJECT/'configs/active_mask_template_requests.json').read_text());root=PROJECT/taskconfig['directory']
    proposals=list(map(json.loads,(root/'proposals.jsonl').read_text().splitlines()));byclass=Counter(p['class_id'] for p in proposals)
    filter_classes=json.loads((root/'manifest.json').read_text()).get('filter_classes',[4,5,7,14,22])
    assert taskconfig['schema']=='preannotated_mask_worklist_v1' and len(proposals)==taskconfig['request_count']
    base=json.loads((PROJECT/'outputs/pallet_mask_gallery_managed_v1/public_access.json').read_text())['public_url']
    stores=[PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3',PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3']
    before={str(p):database_fingerprint(p) for p in stores}
    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:
        p=urlsplit(proxy_url);launch['proxy']=dict(server=f'{p.scheme}://{p.hostname}:{p.port}',bypass='127.0.0.1,localhost')
        if p.username is not None:launch['proxy']['username']=unquote(p.username)
        if p.password is not None:launch['proxy']['password']=unquote(p.password)
    def wait(page,condition):
        deadline=time.monotonic()+90
        while time.monotonic()<deadline:
            if page.evaluate(condition):return
            time.sleep(.1)
        raise AssertionError(condition)
    writes=[];errors=[];checks=[]
    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 route in ('**/api/review/annotations/**','**/api/annotations/**','**/api/delete-object/**','**/api/restore-object/**'):context.route(route,deny)
            page.goto(base+'/template-requests/?batch='+args.batch,wait_until='domcontentloaded',timeout=90000)
            wait(page,f'window.maskGalleryDiagnostics && document.querySelectorAll(".mg-edit-button[data-key]").length==={len(proposals)}')
            page.evaluate('document.fonts.ready');assert '已预标注' in page.locator('h1').inner_text() and page.locator('article').count()==len(proposals)
            assert page.locator('#request-filter option').evaluate_all('(options)=>options.map(o=>o.value)')==['']+[str(c) for c in filter_classes]
            for cls in filter_classes:
                page.locator('#request-filter').select_option(str(cls));assert page.locator('article:visible').count()==byclass[cls]
            page.locator('#request-filter').select_option('');assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
            page.screenshot(path=str(out/f'public_preannotated_tasks_{width}.png'))
            for index,cls in enumerate(sorted(byclass)):
                proposal=next(p for p in proposals if p['class_id']==cls);key=proposal['target_key']
                page.locator(f'.mg-edit-button[data-key="{key}"]').click()
                if index==0:
                    wait(page,'document.querySelector("#mgLogin").open')
                    page.locator('#mgAccessKey').fill((PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip())
                    page.locator('#mgLoginSubmit').click()
                wait(page,f'maskGalleryDiagnostics().target==="{key}" && !maskGalleryDiagnostics().loading && maskGalleryDiagnostics().imageStatus==="ready"')
                detail=page.evaluate('async key=>(await fetch("/api/review/targets/"+key)).json()',key)
                assert detail['assistant_preannotation_source'] and detail['proposal_polygon']==proposal['polygon']
                d=page.evaluate('maskGalleryDiagnostics()');assert d['polygon']==proposal['polygon'] and not d['dirty']
                assert '预标注草稿' in page.locator('#mgState').inner_text() and d['revision']==0 and detail['history']==[]
                assert page.locator('#mgReset').inner_text()=='恢复预标注草稿'
                page.locator('#mgZoomIn').click();page.locator('#mgZoomOut').click()
                assert page.evaluate('maskGalleryDiagnostics().polygon')==proposal['polygon']
                assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
                page.locator('#mgCanvas').scroll_into_view_if_needed();page.screenshot(path=str(out/f'public_prelabel_class{cls}_{width}.png'))
                page.locator('#mgClose').click()
                after=page.evaluate('async key=>(await fetch("/api/review/targets/"+key)).json()',key)
                assert after['review'] is None and after['history']==[]
                checks.append(dict(width=width,class_id=cls,target_key=key,drawn_polygon_loaded_not_original_box=True,
                    no_fake_save_on_view_or_close=True,independent_mask_editor=True,no_overflow=True))
            context.close()
        browser.close()
    assert not errors and not writes and before=={str(p):database_fingerprint(p) for p in stores}
    value=dict(state='passed',preannotated_tasks=len(proposals),class_counts=dict(byclass),all_task_filters_correct=True,checks=checks,
        sources_unchanged=True,production_annotation_writes=0,annotation_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()
