"""Fast read-only public UI acceptance, separate from exhaustive static asset checks."""
import json
import os
from pathlib import Path
import sys
import time
from urllib.parse import urlsplit,unquote

PROJECT=Path(__file__).resolve().parents[1]


def main():
    import argparse
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output',type=Path,default=PROJECT/'outputs/pallet_mask_remaining_expand_deployment_v1')
    parser.add_argument('--version',type=int,default=10)
    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/'public_ui_acceptance.json'
    if result.exists():raise ValueError('Preserve completed public UI evidence')
    config=json.loads((PROJECT/'configs/active_mask_gallery.json').read_text());root=PROJECT/config['directory']
    if config['publication_version']!=args.version:raise ValueError('Unexpected active publication')
    proposals=list(map(json.loads,(root/'proposals.jsonl').read_text().splitlines()))
    new=list(map(json.loads,(root/'new_proposals.jsonl').read_text().splitlines()))
    manual=list(map(json.loads,(root/'manual_proposals.jsonl').read_text().splitlines()))
    target=(new or manual or proposals)[0];base=json.loads((PROJECT/'outputs/pallet_mask_gallery_managed_v1/public_access.json').read_text())['public_url']
    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):
        end=time.monotonic()+90
        while time.monotonic()<end:
            if page.evaluate(condition):return
            time.sleep(.1)
        raise AssertionError(condition)
    checks=[];errors=[];writes=[]
    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):
            ctx=browser.new_context(viewport=dict(width=width,height=900),is_mobile=width==390,has_touch=width==390)
            page=ctx.new_page();page.on('pageerror',lambda e:errors.append(str(e)))
            def deny(route):
                writes.append(route.request.url);route.fulfill(status=403,content_type='application/json',body='{"error":"read-only acceptance"}')
            page.route('**/api/review/annotations/**',deny)
            page.goto(base+f'/?revision={args.version}#new-batch',wait_until='domcontentloaded',timeout=90000)
            wait(page,f'window.maskGalleryDiagnostics && document.querySelectorAll(".mg-edit-button[data-key]").length==={len(proposals)}')
            assert page.locator('#only-new').is_checked() and page.locator('article:visible').count()==len(new)
            for cls in range(1,23):
                page.locator('#filter').select_option(str(cls));assert page.locator('article:visible').count()==sum(p['class_id']==cls for p in new)
            page.locator('#filter').select_option('');page.locator('#only-new').uncheck()
            assert page.locator('article:visible').count()==len(proposals)
            if new:page.locator('#only-new').check()
            page.locator(f'.mg-edit-button[data-key="{target["target_key"]}"]').click()
            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,'maskGalleryDiagnostics().open && !maskGalleryDiagnostics().loading && maskGalleryDiagnostics().imageStatus==="ready"')
            d=page.evaluate('maskGalleryDiagnostics()')
            assert not d['dirty'] and d['polygon']==target['polygon']
            page.locator('#mgFit').click();assert page.evaluate('maskGalleryDiagnostics().polygon')==target['polygon']
            assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
            page.locator('#mgCanvas').scroll_into_view_if_needed();page.screenshot(path=str(out/f'public_quick_editor_{width}.png'))
            page.locator('#mgClose').click();assert not page.evaluate('maskGalleryDiagnostics().open')
            checks.append(dict(width=width,default_new_count=len(new),all_class_filters_correct=True,
                cumulative_count=len(proposals),editor_loaded=True,no_overflow=True,no_annotation_save=True))
            ctx.close()
        browser.close()
    if errors or writes:raise AssertionError(dict(errors=errors,writes=writes))
    value=dict(state='passed',publication_version=args.version,url=base+f'/?revision={args.version}#new-batch',checks=checks,
        all_22_class_filters_verified=True,page_errors=errors,production_annotation_writes=0,
        exhaustive_asset_acceptance_separate=True)
    result.write_text(json.dumps(value,ensure_ascii=False,indent=2));print(json.dumps(value),flush=True)


if __name__=='__main__':main()
