"""Actual Chromium stale-tab regression using r9/r13 human states in TEMP stores only."""
from contextlib import closing
from http.server import ThreadingHTTPServer
import json
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_class_correction import ROOT,STATE
from pallet.mask_class_correction_review import ClassGallery,ClassHandler,compute
from pallet.mask_model_training_data import read,write,require
from pallet.mask_template_refined import readonly
from pallet.mask_quality_recovery import fingerprint
from pallet.cluster_targets import digest
from check_mask_under50_ui import wait_value

OUT=PROJECT/'outputs/pallet_mask_class_correction_checks_v1/interface_v3/destination_sync'


def check():
    require(not (OUT/'acceptance.json').exists(),'Preserve destination sync evidence');OUT.mkdir(mode=0o700,parents=True,exist_ok=True)
    with closing(readonly(STATE/'mask_reviews.sqlite3')) as db:
        states={revision:json.loads(raw)['state'] for revision,raw in db.execute("SELECT revision,payload FROM events WHERE target_key='class_graph' AND revision IN (9,13)")}
    require(set(states)=={9,13},'Real historical reproduction states unavailable')
    before=fingerprint(STATE/'mask_reviews.sqlite3');sources=read(ROOT/'input_manifest.json')['source_fingerprints']
    source_before={path:fingerprint(PROJECT/path) for path in sources};key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    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
    results=[];errors=[]
    with tempfile.TemporaryDirectory(prefix='class-destination-sync-',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=ClassGallery(ROOT,Path(scratch)/str(width),key)
            require(gallery.editor.version()['revision']==0,'Only fresh temp class stores allowed')
            def seed(state,expected):
                gallery.editor.store.save('class_graph',expected,dict(state=state,reviewer='SYNTHETIC history playback only',action='synthetic_history_fixture',note='r9/r13 readonly states copied to temp only',binding=gallery.manifest_sha256,source_records_sha256=gallery.manifest['source_records_sha256'],old_classes_overwritten=False,human_polygons_modified=False,automatic_training_or_GT_promotion=False))
            seed(states[9],0);oldgs,_=compute(gallery.records,states[9]);newgs,_=compute(gallery.records,states[13])
            one=next(g for g in newgs.values() if g['proposed_class_id']==1);require(one['K']==8 and one['targets']==100,'Expected real new K8 Class1 fixture')
            require(not any(g['proposed_class_id']==1 for g in oldgs.values()),'Old history already has Class1')
            stable=next(r for r in gallery.records if r['actual_K']==8 and states[9]['assignments'][r['target_key']]==states[13]['assignments'][r['target_key']] and states[13]['assignments'][r['target_key']]!=one['face_id'])
            face=states[9]['assignments'][stable['target_key']]
            class QuietHandler(ClassHandler):
                def log_message(self,*args):pass
            server=ThreadingHTTPServer(('127.0.0.1',0),QuietHandler);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 error:errors.append(str(error)))
            try:
                require(context.request.get(base+'/api/review/version').status==401,'Version endpoint must require authentication')
                page.goto(base,wait_until='domcontentloaded');page.locator('#key').fill(key);page.locator('#loginButton').click()
                wait_value(page,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().revision===1')
                page.locator('#filterK').select_option('8');page.locator('#groupSelect').select_option(face)
                old_option=page.locator('#destinationClass option[value="1"]')
                require(old_option.count()==0 or old_option.get_attribute('data-kind')=='reuse_old_class','Stale history must not have an existing Class1 destination')
                page.locator('#reviewer').fill('SYNTHETIC draft reviewer');page.locator('#note').fill('SYNTHETIC draft must survive destination synchronization')
                page.locator('#cards .card[data-key="'+stable['target_key']+'"] img').first.click()
                seed(states[13],1)
                page.locator('#destinationClass').focus()
                wait_value(page,'classCorrectionDiagnostics().catalogRevision===2&&!classCorrectionDiagnostics().checking')
                require(page.evaluate('classCorrectionDiagnostics().revision')==1 and page.evaluate('classCorrectionDiagnostics().selected')==[stable['target_key']],'Destination sync silently rebased draft')
                require(page.locator('#note').input_value()=='SYNTHETIC draft must survive destination synchronization','Draft note lost')
                require(page.locator('#destination option[value="'+one['face_id']+'"]').count()==1 and not page.locator('#destination option[value="'+one['face_id']+'"]').is_disabled(),'New K8 Class1 missing from face list')
                require(page.locator('#destinationClass option[value="1"]').count()==1 and not page.locator('#destinationClass option[value="1"]').is_disabled(),'New K8 Class1 missing from class list')
                require(page.locator('#destinationClass option[value="1"]').get_attribute('data-kind')=='existing_face','New actual Class1 must replace any unoccupied oldClass reuse option')
                require('本页r1，目标列表r2' in page.locator('#destinationInfo').inner_text(),'Catalog/base revision distinction missing')
                require(page.locator('#confirmedCards .card[data-class-id="1"]').count()==1,'Confirmed reference shelf not synchronized')
                page.locator('#destinationClass').select_option('1');page.locator('#moveClass').click()
                wait_value(page,'document.getElementById("status").textContent.includes("版本冲突")')
                require(gallery.editor.version()['revision']==2 and len(gallery.editor.history())==2,'Stale draft submitted to real temp event store')
                page.screenshot(path=str(OUT/f'new_class1_catalog_old_draft_{width}.png'))
                page.locator('#refresh').click();wait_value(page,'classCorrectionDiagnostics().revision===2')
                require(page.evaluate('classCorrectionDiagnostics().selected')==[stable['target_key']] and page.locator('#destinationClass').input_value()=='1','Explicit refresh lost unchanged target/class draft')
                graph=gallery.editor.get();expected=[g for g in graph['groups'].values() if g['K']==8]
                for other in expected:
                    page.locator('#groupSelect').select_option(other['face_id'])
                    check=page.evaluate('''()=>{const g=classCorrectionView().graph,face=classCorrectionDiagnostics().face,groups=Object.values(g.groups).filter(x=>x.K===g.groups[face].K);const a=[...document.querySelectorAll('#destination option')].slice(1),b=[...document.querySelectorAll('#destinationClass option')].slice(1);return {count:a.length,groups:groups.length,ordered:b.filter(x=>!x.value.startsWith('pending:')).map(x=>Number(x.value)),class1:b.find(x=>x.value==='1')?.disabled,face1:a.find(x=>x.textContent.startsWith('Class 1 ·'))?.disabled,self:a.find(x=>x.value===face)?.disabled}}''')
                    require(check['count']==check['groups'] and check['ordered']==sorted(check['ordered']) and check['self'],'Same-K destination completeness/order/self exclusion incorrect')
                    require(check['class1']==(other['proposed_class_id']==1) and check['face1']==(other['proposed_class_id']==1),'Class1 disappears from another K8 group')
                page.locator('#groupSelect').select_option(face);sourceclass=next(str(c) for c in graph['groups'][face]['old_class_counts'])
                page.locator('#filterClass').select_option(sourceclass);page.locator('#groupSelect').select_option(face)
                require(not page.locator('#destinationClass option[value="1"]').is_disabled(),'Old-class filter incorrectly hides destination')
                page.locator('#filterStatus').select_option('pending');require(not page.locator('#destinationClass option[value="1"]').is_disabled(),'Status filter incorrectly hides confirmed Class1 destination')
                require(page.evaluate('document.documentElement.scrollWidth<=innerWidth'),'Horizontal overflow')
                page.screenshot(path=str(OUT/f'class1_list_complete_sorted_{width}.png'))
                require(len(gallery.editor.history())==2,'Readonly option validation wrote events')
                results.append(dict(width=width,historical_state_revisions=[9,13],all_K8_groups_checked=len(expected),new_Class1_visible_in_both_lists=True,stale_tab_auto_destination_sync=True,draft_note_selection_base_revision_preserved=True,stale_save_blocked_without_POST=True,explicit_refresh_preserves_unchanged_selection=True,current_group_visible_disabled=True,Class_number_sort=True,oldClass_and_status_filters_do_not_hide_destinations=True,temporary_fixture_events=2))
                print('Class1 stale-tab destination sync passed',width,flush=True)
            finally:context.close();server.shutdown();server.server_close();worker.join()
        browser.close()
    require(before==fingerprint(STATE/'mask_reviews.sqlite3') and source_before=={path:fingerprint(PROJECT/path) for path in sources} and not errors,'Real state changed or browser error')
    write(OUT/'acceptance.json',dict(state='passed_actual_Chromium_Class1_stale_catalog_regression_temp_only',viewports=results,page_errors=errors,production_writes=0,production_class_decision_POST_attempts=0,real_store_unchanged=True,ui_extension_sha256=gallery.ui_extension_sha256,manifest_sha256=digest(ROOT/'manifest.json'),review_implementation_sha256=digest(PROJECT/'pallet/mask_class_correction_review.py'),code_sha256=digest(__file__)))


if __name__=='__main__':
    import argparse
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--output',type=Path);a=p.parse_args()
    if a.output:OUT=a.output.resolve()
    try:check()
    except Exception as error:
        OUT.mkdir(mode=0o700,parents=True,exist_ok=True)
        if not (OUT/'failure.json').exists():write(OUT/'failure.json',dict(error=str(error),production_class_decision_POST_attempts=0))
        raise
