"""Actual desktop/narrow Chromium pilot; all edits confined to temporary stores."""
from http.server import ThreadingHTTPServer
import os
from pathlib import Path
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_taxonomy_data import REQUESTS,MANAGED,sources_current
from pallet.mask_taxonomy_review import TaxonomyGallery,TaxonomyHandler
from pallet.mask_model_training_data import require,read,write
from pallet.cluster_targets import digest
from check_mask_under50_ui import wait_value


def check(out):
    require(not (out/'ui_acceptance.json').exists(),'Preserve existing UI evidence');out.mkdir(mode=0o700,parents=True,exist_ok=True)
    require(sources_current(),'Source changed before UI test')
    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
    secret=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    errors=[];results=[]
    with tempfile.TemporaryDirectory(prefix='taxonomy-pilot-',dir='/tmp/opencode') as scratch,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=TaxonomyGallery(REQUESTS,Path(scratch)/str(width),secret)
            class Quiet(TaxonomyHandler):
                def log_message(self,*args):pass
            server=ThreadingHTTPServer(('127.0.0.1',0),Quiet);server.gallery=gallery;server.daemon_threads=True
            worker=threading.Thread(target=server.serve_forever,daemon=True);worker.start();base=f'http://127.0.0.1:{server.server_port}'
            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)))
            try:
                require(context.request.get(base+'/api/review/catalog').status==401,'Task metadata must require original credential')
                page.goto(base,wait_until='domcontentloaded');page.locator('#key').fill(secret);page.locator('#loginButton').click();wait_value(page,'window.taxonomyDiagnostics&&taxonomyDiagnostics().loaded')
                require(page.locator('#quotas tr').count()==41,'Must report all41 fine-class gaps')
                props=list(gallery.proposals.values());p=props[0];key=p['target_key'];k=p['K'];same=next(c for c in gallery.classes.values() if c['train_enabled'] and c['K']==k and c['class_id']!=p['class_id']);different=next(c for c in gallery.classes.values() if c['train_enabled'] and c['K']!=k)
                page.locator('#classFilter').select_option(str(p['class_id']));page.locator('#cards button').first.click();wait_value(page,'taxonomyDiagnostics().detail&&document.getElementById("original").naturalWidth>0')
                key=page.evaluate('taxonomyDiagnostics().detail');p=gallery.proposals[key];k=p['K']
                require(page.locator('#examples img').count()>0 and page.locator('#originalNote').inner_text(),'Class examples/original notes missing')
                require(page.evaluate('getComputedStyle(document.getElementById("originalNote")).fontFamily.includes("Review")'),'Original Chinese note uses unreadable default monospace font')
                page.locator('#reviewer').fill('SYNTHETIC temp-only pilot');page.locator('#note').fill('')
                page.locator('#correct').click();wait_value(page,'taxonomyDiagnostics().revision===1&&!taxonomyDiagnostics().saving')
                require(gallery.editor.store.get(key)['note']=='','Empty optional note failed')
                page.locator('#editClass').select_option(str(different['class_id']));page.locator('#correct').click();wait_value(page,'document.getElementById("saveStatus").textContent.includes("保存失败")&&!taxonomyDiagnostics().saving')
                require(gallery.editor.store.get(key)['revision']==1,'WrongK class change overwrote saved contour')
                page.reload(wait_until='domcontentloaded');wait_value(page,'window.taxonomyDiagnostics&&taxonomyDiagnostics().loaded');page.locator('#classFilter').select_option(str(p['class_id']));page.locator('#cards button').first.click();wait_value(page,'taxonomyDiagnostics().detail')
                require(page.evaluate('taxonomyDiagnostics().class_id')==different['class_id'],'Failed save draft was lost on reload')
                page.locator('#editClass').select_option(str(same['class_id']));page.locator('#correct').click();wait_value(page,'taxonomyDiagnostics().revision===2&&!taxonomyDiagnostics().saving')
                require(gallery.editor.store.get(key)['class_id']==same['class_id'],'Human class change not saved as sidecar')
                page.locator('#history').select_option('1');page.locator('#restore').click();page.locator('#correct').click();wait_value(page,'taxonomyDiagnostics().revision===3&&!taxonomyDiagnostics().saving')
                require(gallery.editor.store.get(key)['restored_from_revision']==1,'History restored by overwriting instead of new revision')
                # Actual pointer adds a vertex on the longest boundary edge.
                import math
                polygon=p['polygon'];a,b=max(zip(polygon,polygon[1:]+polygon[:1]),key=lambda e:math.dist(e[0],e[1]));point=[(a[j]+b[j])/2 for j in (0,1)]
                canvas=page.locator('#canvas');canvas.scroll_into_view_if_needed();rect=canvas.bounding_box();w,h=p['source']['size'];scale=min(900/w,540/h)*.94;dx=(900-w*scale)/2;dy=(540-h*scale)/2
                first=polygon[0];px=rect['x']+(dx+first[0]*scale)*rect['width']/900;py=rect['y']+(dy+first[1]*scale)*rect['height']/540
                before=page.evaluate('JSON.stringify(JSON.parse(localStorage.getItem(Object.keys(localStorage).find(k=>k.endsWith(taxonomyDiagnostics().detail)))).polygon)')
                page.mouse.move(px,py);page.mouse.down();page.mouse.move(px+5,py+2,steps=4);page.mouse.up()
                after=page.evaluate('JSON.stringify(JSON.parse(localStorage.getItem(Object.keys(localStorage).find(k=>k.endsWith(taxonomyDiagnostics().detail)))).polygon)')
                require(before!=after,'Actual vertex drag did not change local draft');page.locator('#undo').click()
                canvas.scroll_into_view_if_needed();rect=canvas.bounding_box()
                page.mouse.click(rect['x']+(dx+point[0]*scale)*rect['width']/900,rect['y']+(dy+point[1]*scale)*rect['height']/540)
                wait_value(page,f'taxonomyDiagnostics().points==={k+1}');page.locator('#remove').click();wait_value(page,f'taxonomyDiagnostics().points==={k}')
                page.locator('#undo').click();wait_value(page,f'taxonomyDiagnostics().points==={k+1}');page.locator('#redo').click();wait_value(page,f'taxonomyDiagnostics().points==={k}')
                other=context.new_page();other.on('pageerror',lambda e:errors.append(str(e)));other.goto(base,wait_until='domcontentloaded');wait_value(other,'window.taxonomyDiagnostics&&taxonomyDiagnostics().loaded');other.locator('#classFilter').select_option(str(p['class_id']));other.locator('#cards button').first.click();wait_value(other,'taxonomyDiagnostics().revision===3')
                page.locator('#draft').click();wait_value(page,'taxonomyDiagnostics().revision===4&&!taxonomyDiagnostics().saving')
                other.locator('#correct').click();wait_value(other,'document.getElementById("saveStatus").textContent.includes("409版本冲突")&&!taxonomyDiagnostics().saving')
                require(gallery.editor.store.get(key)['revision']==4 and len(gallery.editor.store.history(key))==4,'Stale tab overwrote history')
                other.close();page.locator('#export').get_attribute('href');require(context.request.get(base+page.locator('#export').get_attribute('href')).status==200,'Human JSON export failed')
                page.screenshot(path=str(out/f'pilot_editor_{width}.png'),full_page=True)
                page.locator('#close').click();page.locator('#stateFilter').select_option('draft');require(page.locator('#cards button').count()==1,'Saved-state filter failed')
                require(page.evaluate('document.documentElement.scrollWidth<=innerWidth'),'Narrow page overflows viewport')
                page.screenshot(path=str(out/f'pilot_catalog_{width}.png'),full_page=True)
                require(context.request.get(base+'/proposals.jsonl').status==404 and context.request.get(base+'/private/class_reviews.sqlite3').status==404,'Private source exposed')
                results.append(dict(width=width,actual_temp_saves=4,empty_optional_note=True,class_change_and_K_recheck=True,
                    local_draft_survives_failed_save_and_reload=True,actual_canvas_add_delete_undo_redo=True,actual_vertex_drag=True,Chinese_original_note_font=True,
                    history_restore_append_only=True,stale409_preserves_draft=True,original_and_class_examples=True,all41_quotas=True))
                print(dict(state='taxonomy_actual_browser_pilot_passed',width=width),flush=True)
            finally:context.close();server.shutdown();server.server_close();worker.join()
        browser.close()
    require(not errors and sources_current(),'Browser error or original source changed')
    write(out/'ui_acceptance.json',dict(state='passed_actual_taxonomy_Chromium_temp_stores',manifest_sha256=digest(REQUESTS/'manifest.json'),
        ui_revision_sha256=digest(REQUESTS/'ui_revision.json') if (REQUESTS/'ui_revision.json').exists() else None,
        review_implementation_sha256=digest(PROJECT/'pallet/mask_taxonomy_review.py'),page_errors=errors,
        viewports=results,production_writes=0,real_iPhone_Safari_tested=False,code_sha256=digest(__file__)))


if __name__=='__main__':
    import argparse
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--output',type=Path,default=MANAGED/'checks_v2');args=p.parse_args()
    try:check(args.output.resolve())
    except Exception:
        import traceback
        out=args.output.resolve();out.mkdir(mode=0o700,parents=True,exist_ok=True)
        index=1
        while (out/f'ui_failure_{index:03d}.json').exists():index+=1
        write(out/f'ui_failure_{index:03d}.json',dict(traceback=traceback.format_exc(),production_writes=0))
        raise
