"""Read-only browser check of real prelabel saves migrated into the canonical gallery."""
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,required=True);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/'saved_gallery_source_ui_acceptance.json'
    if result.exists():raise ValueError('Preserve completed saved-source UI evidence')
    config=json.loads((PROJECT/'configs/active_mask_gallery.json').read_text());root=PROJECT/config['directory']
    manual=[json.loads(s) for s in (root/'manual_proposals.jsonl').read_text().splitlines()]
    assert manual and len(manual)==json.loads((root/'manifest.json').read_text())['manual_proposals']
    assert all(p['schema']=='saved_gallery_mask_entry_v1' for p in manual)
    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};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):
        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"}')
            context.route('**/api/review/annotations/**',deny)
            page.goto(base+f'/?revision={config["publication_version"]}',wait_until='domcontentloaded',timeout=90000)
            wait(page,'window.maskGalleryDiagnostics && document.querySelector("#only-new")')
            page.locator('#only-new').uncheck()
            for index,cls in enumerate(sorted({p['class_id'] for p in manual})):
                proposal=next(p for p in manual if p['class_id']==cls);key=proposal['target_key'];page.locator('#filter').select_option(str(cls))
                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);history=detail['history']
                assert detail['saved_gallery_manual_source'] and not detail['saved_pose_manual_source'] and not detail['assistant_preannotation_source']
                assert detail['proposal_polygon']==proposal['polygon'] and detail['review']['polygon']==proposal['polygon']
                assert detail['template'] is None and history and not detail['proposal_dependency_stale']
                diagnostics=page.evaluate('maskGalleryDiagnostics()');assert not diagnostics['dirty'] and diagnostics['polygon']==proposal['polygon']
                assert page.locator('#mgReset').inner_text()=='恢复人工掩膜快照' and '已保存' in page.locator('#mgState').inner_text()
                assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
                page.locator('#mgCanvas').scroll_into_view_if_needed();page.screenshot(path=str(out/f'public_saved_gallery_class{cls}_{width}.png'))
                page.locator('#mgClose').click()
                after=page.evaluate('async key=>(await fetch("/api/review/targets/"+key)).json()',key)
                assert after['review']==detail['review'] and after['history']==history
                checks.append(dict(width=width,class_id=cls,target_key=key,actual_saved_polygon_loaded=True,all_history_preserved=True,
                    not_a_pose_or_machine_source=True,view_close_does_not_save=True,no_overflow=True))
            context.close()
        browser.close()
    assert not writes and not errors and before=={str(p):database_fingerprint(p) for p in stores}
    value=dict(state='passed',checks=checks,saved_gallery_sources=len(manual),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()
