"""Read-only public smoke check of an original-human source in the gallery."""
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_quota_deployment_v1')
    parser.add_argument('--target',help='Check one actual manual-source target instead of the first')
    args=parser.parse_args();out=args.output.resolve()
    if not out.is_relative_to(PROJECT/'outputs'):raise ValueError('Expected validation output directory')
    result=out/('manual_source_'+args.target+'_ui_acceptance.json' if args.target else 'manual_source_ui_acceptance.json')
    if result.exists():raise ValueError('Preserve completed acceptance')
    config=json.loads((PROJECT/'configs/active_mask_gallery.json').read_text());root=PROJECT/config['directory']
    total=json.loads((root/'verification.json').read_text())['proposals_verified'];version=config['publication_version']
    manual_sources=list(map(json.loads,(root/'manual_proposals.jsonl').read_text().splitlines()))
    manual=next((p for p in manual_sources if p['target_key']==args.target),None) if args.target else manual_sources[0]
    if manual is None:raise ValueError('Requested manual target is absent')
    key=manual['target_key']
    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
    def wait(page,condition):
        end=time.monotonic()+90
        while time.monotonic()<end:
            if page.evaluate(condition):return
            time.sleep(.1)
        raise AssertionError(condition)
    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)
    writes=[];errors=[]
    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)
        page=browser.new_page(viewport=dict(width=1400,height=1000));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={version}',wait_until='domcontentloaded',timeout=90000)
        wait(page,f'window.maskGalleryDiagnostics && document.querySelectorAll(".mg-edit-button[data-key]").length==={total}')
        page.locator('#only-new').uncheck();page.locator(f'.mg-edit-button[data-key="{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().imageStatus==="ready" && !maskGalleryDiagnostics().loading')
        d=page.evaluate('maskGalleryDiagnostics()');assert d['polygon']==manual['polygon'] and not d['dirty'] and d['revision']==0
        if manual.get('original_rectangle_review_only'):
            assert '已复核保留原框' in page.locator('#mgState').inner_text()
            assert page.locator('#mgReset').inner_text()=='恢复已复核原框'
        else:
            assert '已在位姿标注保存人工掩膜' in page.locator('#mgState').inner_text()
            assert page.locator('#mgReset').inner_text()=='恢复人工模板快照'
        assert page.locator('#mgHistory button').count()==0
        screenshot='manual_source_editor_'+args.target+'.png' if args.target else 'manual_source_editor.png'
        page.locator('#mgCanvas').scroll_into_view_if_needed();page.screenshot(path=str(out/screenshot))
        page.locator('#mgClose').click();assert not page.evaluate('maskGalleryDiagnostics().open')
        assert not writes and not errors
        browser.close()
    result.write_text(json.dumps(dict(state='passed',target_key=key,actual_pose_polygon_loaded=True,
        separate_gallery_history_not_fabricated=True,original_pose_saved_status_displayed=True,production_annotation_writes=0,page_errors=errors),indent=2))
    print('Public manual-source editor check passed; no annotations written',flush=True)


if __name__=='__main__':main()
