"""Synthetic-copy browser save/failure checks for preannotated worklists; no production saves."""
from contextlib import closing
import json
import os
from pathlib import Path
import sqlite3
import sys
import tempfile
import threading
import time

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.mask_gallery import Gallery,GalleryServer
from pallet.cluster_targets import digest
from pallet.pose_review_geometry import canonical
from scripts.build_mask_template_requests import database_fingerprint

ROOT=PROJECT/'outputs/pallet_mask_remaining_round3_v1'
TASKS=PROJECT/'outputs/pallet_mask_preannotated_requests_v1'
OUT=PROJECT/'outputs/pallet_mask_remaining_round3_deployment_v1'


def config():
    return dict(schema='preannotated_mask_worklist_v1',directory=str(TASKS.relative_to(PROJECT)),
        manifest_sha256=digest(TASKS/'manifest.json'),verification_sha256=digest(TASKS/'verification.json'),completed_request_count=0)


def main():
    import argparse
    global ROOT,TASKS,OUT
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--gallery',type=Path,default=ROOT);parser.add_argument('--tasks',type=Path,default=TASKS);parser.add_argument('--output',type=Path,default=OUT)
    args=parser.parse_args();ROOT,TASKS,OUT=(p.resolve() for p in (args.gallery,args.tasks,args.output))
    if not all(p.is_relative_to(PROJECT/'outputs') for p in (ROOT,TASKS,OUT)):raise ValueError('Use explicit output directories')
    OUT.mkdir(exist_ok=True)
    result=OUT/'preannotation_editor_synthetic_acceptance.json'
    if result.exists():raise ValueError('Preserve completed synthetic UI evidence')
    live=PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3'
    pose=PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
    before={str(p):database_fingerprint(p) for p in (live,pose)}
    proposals=list(map(json.loads,(TASKS/'proposals.jsonl').read_text().splitlines()));first=proposals[0];key=first['target_key']
    counted=json.loads((ROOT/'manifest.json').read_text())['proposals'];task_count=len(proposals)
    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
    errors=[];checks=[]
    def wait(page,condition):
        deadline=time.monotonic()+60
        while time.monotonic()<deadline:
            if page.evaluate(condition):return
            time.sleep(.08)
        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 width in (1400,390):
            with tempfile.TemporaryDirectory(prefix='preannotation-synthetic-',dir='/tmp/opencode') as temporary:
                temp=Path(temporary);reviews=temp/'reviews';reviews.mkdir();settings=temp/'tasks.json';settings.write_bytes(canonical(config()))
                with closing(sqlite3.connect(live.as_uri()+'?mode=ro',uri=True)) as src,closing(sqlite3.connect(reviews/'mask_reviews.sqlite3')) as dst:src.backup(dst)
                gallery=Gallery(ROOT,reviews,'preannotation-synthetic-access-secret-123456',settings)
                assert gallery.count==counted and len(gallery.editor.proposals)==counted+task_count and gallery.manual_request_count==task_count
                server=GalleryServer(('127.0.0.1',0),gallery);thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
                ctx=browser.new_context(viewport=dict(width=width,height=1000),is_mobile=width==390,has_touch=width==390)
                page=ctx.new_page();page.on('pageerror',lambda error:errors.append(str(error)))
                try:
                    base=f'http://127.0.0.1:{server.server_port}';page.goto(base+'/template-requests/',wait_until='domcontentloaded')
                    wait(page,f'window.maskGalleryDiagnostics && document.querySelectorAll(".mg-edit-button[data-key]").length==={task_count}')
                    assert '已预标注' in page.locator('h1').inner_text() and page.locator('article').count()==task_count
                    page.locator(f'.mg-edit-button[data-key="{key}"]').click();wait(page,'document.querySelector("#mgLogin").open')
                    page.locator('#mgAccessKey').fill(gallery.editor.access_key);page.locator('#mgLoginSubmit').click()
                    wait(page,'maskGalleryDiagnostics().open && !maskGalleryDiagnostics().loading && maskGalleryDiagnostics().imageStatus==="ready"')
                    assert page.evaluate('maskGalleryDiagnostics().polygon')==first['polygon']
                    assert not page.evaluate('maskGalleryDiagnostics().dirty') and '预标注草稿' in page.locator('#mgState').inner_text()
                    assert page.locator('#mgReset').inner_text()=='恢复预标注草稿' and page.locator('#mgHistory button').count()==0
                    assert gallery.editor.store.get(key) is None and page.evaluate('document.documentElement.scrollWidth<=innerWidth')
                    route='**/api/review/annotations/'+key
                    page.route(route,lambda route:route.fulfill(status=409,content_type='application/json',body='{"error":"synthetic save conflict"}'))
                    page.locator('#mgNext').click();wait(page,'maskGalleryDiagnostics().dirty && !maskGalleryDiagnostics().saving && maskGalleryDiagnostics().conflict')
                    assert page.evaluate('maskGalleryDiagnostics().target')==key and page.evaluate('maskGalleryDiagnostics().polygon')==first['polygon']
                    assert page.evaluate('Object.keys(localStorage).some(k=>k.startsWith("mask-gallery-v1:"))') and gallery.editor.store.get(key) is None
                    page.screenshot(path=str(OUT/f'synthetic_preannotation_save_failure_{width}.png'))
                    # Reload proves the local draft survives. Resolve against the
                    # unchanged synthetic server, then explicitly save a real r1
                    # only into the isolated temporary database.
                    page.unroute(route);page.once('dialog',lambda dialog:dialog.accept());page.locator('#mgResolve').click()
                    wait(page,'!maskGalleryDiagnostics().conflict && !maskGalleryDiagnostics().loading')
                    page.locator('#mgSave').click();wait(page,'maskGalleryDiagnostics().revision===1 && !maskGalleryDiagnostics().dirty')
                    saved=gallery.editor.store.get(key)
                    assert saved['polygon']==first['polygon'] and saved['preannotation_provenance']['worklist_manifest_sha256']==digest(TASKS/'manifest.json')
                    assert saved['human_edited'] and not saved['human_mask_confirmed'] and not saved['pose_store_written']
                    page.locator('#mgNext').click();wait(page,f'maskGalleryDiagnostics().target!=="{key}" && !maskGalleryDiagnostics().loading && maskGalleryDiagnostics().imageStatus==="ready"')
                    other=page.evaluate('maskGalleryDiagnostics().target');assert gallery.editor.store.get(other) is None
                    page.locator('#mgClose').click();assert gallery.editor.store.get(other) is None
                    checks.append(dict(width=width,preannotated_polygon_loaded=True,save_failure_blocks_next=True,local_draft_retained=True,
                        explicit_save_isolated_to_synthetic_copy=True,unchanged_draft_saved_only_by_explicit_action=True,
                        source_pose_unchanged=True,no_fake_history_on_view_or_close=True,no_overflow=True))
                finally:ctx.close();server.shutdown();server.server_close();thread.join()
        browser.close()
    assert not errors and {str(p):database_fingerprint(p) for p in (live,pose)}==before
    value=dict(state='passed',checks=checks,synthetic_copy_only=True,production_annotation_writes=0,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()
