"""Actual Chromium actionability; successful saves only in /tmp synthetic stores."""
from collections import Counter
from contextlib import closing
from http.server import ThreadingHTTPServer
import json
import math
import os
from pathlib import Path
import sqlite3
import sys
import tempfile
import threading

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.mask_model_review import ModelMaskGallery,ModelMaskHandler
from pallet.mask_gallery_review import MaskReviewStore
from pallet.cluster_targets import digest
from pallet.pose_review_geometry import canonical
from pallet.mask_quality_recovery import fingerprint,POSE,GALLERY
from check_mask_under50_ui import wait_value

ROOT=PROJECT/'outputs/pallet_mask_model_requests_v1';OUT=PROJECT/'outputs/pallet_mask_model_ui_acceptance_v3'
REVIEWS=PROJECT/'outputs/pallet_mask_model_reviews_v1'


def event_count(path):
    with closing(sqlite3.connect(path.resolve().as_uri()+'?mode=ro',uri=True)) as db:return db.execute('SELECT count(*) FROM events').fetchone()[0]


def check(gallery_class=ModelMaskGallery,keypoint_mode=False,allow_human_keypoint_edits=False,local_draft_prefix=None,
        editing_class=1,image_retry_class=2):
    if OUT.exists():raise ValueError('Preserve all previous UI success/failure evidence')
    OUT.mkdir(mode=0o700)
    key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    gallery=gallery_class(ROOT,REVIEWS,key);real_store=gallery.editor.store
    before=dict(pose=fingerprint(POSE),gallery=fingerprint(GALLERY),new_model=fingerprint(real_store.path))
    props=list(gallery.proposals.values());counts=Counter(p['class_id'] for p in props)
    errors=[];results=[]
    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
    with tempfile.TemporaryDirectory(prefix='model-mask-ui-only-',dir='/tmp/opencode') as scratch:
        class TestHandler(ModelMaskHandler):
            def log_message(self,*_):pass
        server=ThreadingHTTPServer(('127.0.0.1',0),TestHandler);server.gallery=gallery;server.daemon_threads=True
        thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start();base=f'http://127.0.0.1:{server.server_port}'
        try:
            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','--disable-features=VizDisplayCompositor'])
                for width,height in ((1400,1000),(390,844)):
                    gallery.editor.store=MaskReviewStore(Path(scratch)/str(width),gallery.editor.formal_manifest_sha256)
                    context=browser.new_context(viewport=dict(width=width,height=height),is_mobile=width==390,has_touch=width==390)
                    page=context.new_page();page.on('pageerror',lambda e:errors.append(str(e)))
                    page.goto(base+'/',wait_until='domcontentloaded');wait_value(page,'window.maskGalleryDiagnostics&&document.querySelectorAll(".mg-edit-button[data-key]").length==='+str(len(props)))
                    assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
                    assert page.locator('article:visible').count()==len(props)
                    for cls in range(1,23):
                        page.locator('#request-filter').select_option(str(cls));assert page.locator('article:visible').count()==counts[cls]
                    page.screenshot(path=str(OUT/f'page_{width}.png'))
                    for cls in sorted(counts):
                        target=next(p['target_key'] for p in props if p['class_id']==cls)
                        page.locator('#request-filter').select_option(str(cls));page.locator(f'.mg-edit-button[data-key="{target}"]').click()
                        if cls==min(counts):
                            wait_value(page,'document.getElementById("mgLogin").open');page.locator('#mgAccessKey').fill(key);page.locator('#mgLoginSubmit').click()
                        wait_value(page,'maskGalleryDiagnostics().open&&!maskGalleryDiagnostics().loading&&maskGalleryDiagnostics().imageStatus==="ready"&&maskGalleryDiagnostics().target==='+json.dumps(target))
                        initial=page.evaluate('maskGalleryDiagnostics()');assert initial['revision']==0 and not initial['dirty']
                        if keypoint_mode:
                            assert len(initial['polygon'])==gallery.standard['classes'][str(cls)]['standard_count']
                            assert page.locator('#mgDeleteVertex').is_disabled()
                            assert page.evaluate('getComputedStyle(document.getElementById("mgTarget")).fontFamily.includes("Review")')
                        page.locator('#mgZoomIn').click();page.locator('#mgZoomOut').click()
                        assert page.evaluate('maskGalleryDiagnostics().polygon')==initial['polygon']
                        assert page.evaluate('document.querySelector("#mgEditor").scrollWidth<=document.querySelector("#mgEditor").clientWidth+2')
                        page.screenshot(path=str(OUT/f'editor_C{cls}_{width}.png'));page.locator('#mgClose').click()
                    # Real pointer geometry edits, undo/redo and add/delete; never
                    # target or invoke the production review store.
                    target=next(p['target_key'] for p in props if p['class_id']==editing_class)
                    page.locator('#request-filter').select_option(str(editing_class));page.locator(f'.mg-edit-button[data-key="{target}"]').click()
                    wait_value(page,'maskGalleryDiagnostics().imageStatus==="ready"&&!maskGalleryDiagnostics().loading')
                    init=gallery.proposals[target].get('initialization')
                    if init and init['kind']=='same_class_template':assert '模板占位' in page.locator('#mgTarget').inner_text()
                    d=page.evaluate('maskGalleryDiagnostics()');x,y=d['screenVertices'][0]
                    page.mouse.move(x,y);page.mouse.down();page.mouse.move(x+.2,y-.2);page.mouse.up()
                    moved=page.evaluate('maskGalleryDiagnostics().polygon');assert moved!=d['polygon']
                    page.locator('#mgUndo').click();assert page.evaluate('maskGalleryDiagnostics().polygon')==d['polygon']
                    page.locator('#mgRedo').click();assert page.evaluate('maskGalleryDiagnostics().polygon')==moved
                    page.locator('#mgUndo').click()
                    # A densely sampled model boundary can have no edge midpoint
                    # outside the 16px vertex hit radius at initial mobile zoom.
                    # Zoom via real controls; do not bypass actionability or alter
                    # the polygon to make a synthetic click pass.
                    midpoint=None
                    for _ in range(10):
                        vertices=page.evaluate('maskGalleryDiagnostics().screenVertices');box=page.locator('#mgCanvas').bounding_box()
                        for i,a in enumerate(vertices):
                            b=vertices[(i+1)%len(vertices)];x,y=(a[0]+b[0])/2,(a[1]+b[1])/2
                            if (box['x']+3<x<box['x']+box['width']-3 and max(0,box['y'])+3<y<min(height,box['y']+box['height'])-3
                                    and min(math.hypot(v[0]-x,v[1]-y) for v in vertices)>18):midpoint=(x,y);break
                        if midpoint:break
                        page.locator('#mgZoomIn').click()
                    assert midpoint is not None,'No genuinely actionable visible model edge after zoom'
                    page.mouse.click(*midpoint)
                    if keypoint_mode and not allow_human_keypoint_edits:
                        assert page.evaluate('maskGalleryDiagnostics().polygon')==d['polygon']
                        page.locator('#mgCanvas').focus();page.keyboard.press('Delete')
                        assert page.evaluate('maskGalleryDiagnostics().polygon')==d['polygon']
                        assert page.locator('#mgDeleteVertex').is_disabled()
                    else:
                        assert len(page.evaluate('maskGalleryDiagnostics().polygon'))==len(d['polygon'])+1
                        page.locator('#mgDeleteVertex').click();assert len(page.evaluate('maskGalleryDiagnostics().polygon'))==len(d['polygon'])
                        if allow_human_keypoint_edits:
                            page.locator('#mgUndo').click()
                            assert len(page.evaluate('maskGalleryDiagnostics().polygon'))==len(d['polygon'])+1
                            page.locator('#mgUndo').click()
                            assert page.evaluate('maskGalleryDiagnostics().polygon')==d['polygon']
                            page.locator('#mgRedo').click()
                            assert len(page.evaluate('maskGalleryDiagnostics().polygon'))==len(d['polygon'])+1
                    poly=page.evaluate('maskGalleryDiagnostics().polygon')
                    page.locator('#mgNote').fill('SYNTHETIC UI ONLY; no production annotation or human count')
                    page.locator('#mgNote').type(' ADFz')
                    assert page.evaluate('maskGalleryDiagnostics().polygon')==poly and page.evaluate('maskGalleryDiagnostics().target')==target
                    def failure(route):route.fulfill(status=503,content_type='application/json',body='{"error":"Synthetic network failure, draft retained"}')
                    page.route('**/api/review/annotations/**',failure);page.locator('#mgNext').click()
                    wait_value(page,'maskGalleryDiagnostics().dirty&&!maskGalleryDiagnostics().saving&&document.getElementById("mgState").textContent.includes("未保存")')
                    assert page.evaluate('maskGalleryDiagnostics().target')==target and page.evaluate('maskGalleryDiagnostics().revision')==0
                    prefix=local_draft_prefix or ('mask-class-keypoints-v3:' if keypoint_mode else 'mask-model-native-v1:')
                    assert page.evaluate('Object.keys(localStorage).some(k=>k.startsWith('+json.dumps(prefix)+'))')
                    page.screenshot(path=str(OUT/f'failed_save_retains_draft_{width}.png'))
                    page.unroute('**/api/review/annotations/**',failure);page.locator('#mgSave').click()
                    wait_value(page,'maskGalleryDiagnostics().revision===1&&!maskGalleryDiagnostics().saving&&!maskGalleryDiagnostics().dirty')
                    saved=gallery.editor.store.get(target);assert len(gallery.editor.store.summary())==1
                    assert saved['model_provenance']['checkpoint_sha256']==gallery.proposals[target]['model_provenance']['checkpoint_sha256']
                    assert saved['human_edited'] and not saved['ground_truth_eligible'] and not saved['automatic_training_eligible']
                    export=context.request.get(base+f'/api/review/export/{target}/labelme.json').json()
                    assert export['shapes'][0]['points']==saved['polygon'] and export['mask_gallery_review']==saved
                    if init:
                        assert saved['initialization_provenance']==init and export['initialization']==init
                        assert saved['image_reuse']==gallery.proposals[target]['image_reuse']==export['image_reuse']
                        assert saved['quality_certified'] is False and export['quality_certified'] is False
                        if init['kind']=='same_class_template':
                            assert saved['template_initialized'] is True and saved['geometry_changed_from_model'] is False
                            assert saved['accepted_model_without_geometry_change'] is False and saved['geometry_changed_from_initialization'] is True
                    if keypoint_mode:
                        assert export['num_keypoints']==len(saved['polygon']) and export['keypoints_xy']==saved['polygon']
                        assert len([s for s in export['shapes'] if s['shape_type']=='point'])==len(saved['polygon'])
                        if allow_human_keypoint_edits:
                            assert len(saved['polygon'])==len(d['polygon'])+1
                            assert saved['human_keypoint_editing']['delta_from_standard']==1
                            assert export['initial_standard_keypoint_count']==len(d['polygon'])
                            assert export['keypoint_count_matches_class_standard'] is False
                            assert detail_initial_count(gallery.editor.detail(target))==len(d['polygon'])
                            # Same genuine app reloads the saved K+1 result, not
                            # the standard-K machine polygon, without changing GT.
                            page.reload(wait_until='domcontentloaded');wait_value(page,'window.maskGalleryDiagnostics')
                            page.locator('#request-filter').select_option(str(editing_class));page.locator(f'.mg-edit-button[data-key="{target}"]').click()
                            wait_value(page,'maskGalleryDiagnostics().revision===1&&maskGalleryDiagnostics().imageStatus==="ready"')
                            assert page.evaluate('maskGalleryDiagnostics().polygon')==saved['polygon']
                        else:
                            detail=gallery.editor.detail(target)
                            rejected=context.request.post(base+'/api/review/annotations/'+target,headers={'X-Review-Request':'1'},data=dict(
                                binding=detail['binding'],source_binding=detail['source_binding'],proposal_id=detail['proposal_id'],
                                expected_revision=1,polygon=saved['polygon'][:4],reviewer='synthetic invalid K must reject',note='not production'))
                            assert rejected.status==400 and gallery.editor.store.get(target)['revision']==1
                    assert context.request.get(base+f'/api/review/export/{target}/mask.png').status==200
                    page.locator('#mgNote').fill('SYNTHETIC revision2');page.locator('#mgSave').click()
                    wait_value(page,'maskGalleryDiagnostics().revision===2&&!maskGalleryDiagnostics().saving')
                    page.locator('#mgEditor details summary').click();page.locator('#mgHistory button').filter(has_text='r1 ·').click();page.locator('#mgSave').click()
                    wait_value(page,'maskGalleryDiagnostics().revision===3&&!maskGalleryDiagnostics().saving')
                    assert gallery.editor.store.get(target)['restored_from_revision']==1 and gallery.editor.store.history(target)[-1]==saved
                    # Same real app in two browser tabs: stale revision cannot overwrite.
                    other=context.new_page();other.goto(base+'/',wait_until='domcontentloaded')
                    wait_value(other,'window.maskGalleryDiagnostics');other.locator('#request-filter').select_option(str(editing_class))
                    other.locator(f'.mg-edit-button[data-key="{target}"]').click();wait_value(other,'maskGalleryDiagnostics().revision===3&&maskGalleryDiagnostics().imageStatus==="ready"')
                    page.locator('#mgNote').fill('SYNTHETIC external tab revision4');page.locator('#mgSave').click()
                    wait_value(page,'maskGalleryDiagnostics().revision===4&&!maskGalleryDiagnostics().saving')
                    other.locator('#mgNote').fill('SYNTHETIC stale tab conflict');other.locator('#mgNext').click()
                    wait_value(other,'maskGalleryDiagnostics().conflict&&!maskGalleryDiagnostics().saving')
                    assert other.evaluate('maskGalleryDiagnostics().target')==target and other.evaluate('maskGalleryDiagnostics().revision')==3
                    assert gallery.editor.store.get(target)['revision']==4
                    other.on('dialog',lambda dlg:dlg.accept());other.locator('#mgResolve').click()
                    wait_value(other,'maskGalleryDiagnostics().revision===4&&!maskGalleryDiagnostics().conflict&&!maskGalleryDiagnostics().dirty')
                    assert other.evaluate('Object.keys(localStorage).some(k=>k.startsWith('+json.dumps(prefix)+')&&k.includes(":backup:"))')
                    other.screenshot(path=str(OUT/f'conflict_resolved_history_{width}.png'));other.close()
                    page.locator('#mgClose').click()
                    # Image load failure is distinct from successful target API loading.
                    second=next(p['target_key'] for p in props if p['class_id']==image_retry_class and p['target_key']!=target)
                    page.locator('#request-filter').select_option(str(image_retry_class))
                    image_pattern='**/images/'+second+'.png*'
                    def image_failure(route):route.fulfill(status=503,body='synthetic image failure')
                    page.route(image_pattern,image_failure);page.locator(f'.mg-edit-button[data-key="{second}"]').click()
                    wait_value(page,'maskGalleryDiagnostics().imageStatus==="error"&&!maskGalleryDiagnostics().loading')
                    assert page.locator('#mgSave').is_disabled()
                    page.unroute(image_pattern,image_failure);page.locator('#mgRetry').click()
                    wait_value(page,'maskGalleryDiagnostics().imageStatus==="ready"');page.locator('#mgClose').click()
                    for path in ('/private/predictions.jsonl','/input_manifest.json','/manifest.json','/../configs/active_mask_gallery.json'):
                        assert context.request.get(base+path).status==404
                    assert len(gallery.editor.store.summary())==1 and len(gallery.editor.store.history(target))==4
                    results.append(dict(width=width,height=height,class_filters_tested=list(range(1,23)),editor_classes_tested=sorted(counts),
                        initialization_kind_edited=init['kind'] if init else None,initialization_truthful_provenance_checked=bool(init),
                        no_horizontal_overflow=True,actual_pointer_drag=True,add_delete_vertex=not keypoint_mode or allow_human_keypoint_edits,
                        initial_machine_proposals_still_exact_class_K=keypoint_mode,
                        human_added_point_save_and_reload=allow_human_keypoint_edits,
                        class_K_lock_enforced=keypoint_mode and not allow_human_keypoint_edits,
                        wrong_K_server_save_rejected=keypoint_mode and not allow_human_keypoint_edits,
                        explicit_point_exports_checked=keypoint_mode,undo_redo=True,zoom_preserves_polygon=True,
                        typed_text_does_not_trigger_image_keys=True,network_failure_no_advance_and_local_draft_preserved=True,
                        successful_saves_to_temporary_simulation_only=4,only_current_target_changed=True,history_restore_is_append_only=True,
                        stale_tab_409_preserves_local_draft=True,conflict_backup_and_reload=True,original_image_failure_retry=True,
                        saved_LabelMe_and_PNG_roundtrip=True,private_resource_404=True))
                    print('Actual isolated browser fullflow passed at viewport',width,flush=True)
                    context.close()
                browser.close()
        finally:server.shutdown();server.server_close();thread.join();gallery.editor.store=real_store
    after=dict(pose=fingerprint(POSE),gallery=fingerprint(GALLERY),new_model=fingerprint(real_store.path))
    protected_same=all(before[name]==after[name] for name in before if not (allow_human_keypoint_edits and name=='new_model'))
    receipt=dict(state='passed_actual_headless_Chromium_isolated_fullflow_not_real_Safari' if not errors and protected_same else 'failed_or_concurrent_source_change',
        viewports=results,page_errors=errors,source_fingerprints_before=before,source_fingerprints_after=after,
        synthetic_success_store_location='/tmp/opencode only; never a production/manual source',production_annotation_writes=0,
        real_model_review_events=event_count(real_store.path),manifest_sha256=digest(ROOT/'manifest.json'),verification_sha256=digest(ROOT/'verification.json'),
        actual_iPhone_or_Safari_tested=False,model_contour_accuracy_certified=False,code_sha256=digest(__file__))
    receipt['concurrent_real_model_review_store_changed']=before['new_model']!=after['new_model']
    with (OUT/'ui_acceptance.json').open('xb') as stream:stream.write(canonical(receipt)+b'\n')
    if errors or not protected_same:raise ValueError('UI errors or external source changes; evidence preserved')
    print(json.dumps(dict(state=receipt['state'],viewports=[r['width'] for r in results],production_annotation_writes=0,synthetic_only_saves=8)))


def detail_initial_count(value):
    assert value['human_keypoint_count_editing_allowed'] is True
    assert len(value['proposal_polygon'])==value['class_keypoint_constraint']['standard_count']
    return value['class_keypoint_constraint']['standard_count']


if __name__=='__main__':
    import argparse
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output',type=Path,default=OUT);args=parser.parse_args()
    OUT=args.output.resolve()
    if OUT.parent!=PROJECT/'outputs' or not OUT.name.startswith('pallet_mask_model_ui_acceptance_'):raise ValueError('Fresh isolated UI evidence directory required')
    try:check()
    except Exception as error:
        if OUT.exists() and not (OUT/'failure.json').exists() and not (OUT/'ui_acceptance.json').exists():
            secret=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
            with (OUT/'failure.json').open('xb') as stream:stream.write(canonical(dict(state='failed_not_public_release',
                error=str(error).replace(secret,'[redacted]'),production_annotation_writes=0,all_successful_save_attempts_isolated_to_tmp=True))+b'\n')
        raise
