"""Replay real18 history in temporary stores; recover and verify refresh persistence."""
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,recoverable_confirmations
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_v4/persistence'


def check():
    require(not (OUT/'acceptance.json').exists(),'Preserve persistence acceptance');OUT.mkdir(mode=0o700,parents=True,exist_ok=True)
    with closing(readonly(STATE/'mask_reviews.sqlite3')) as db:events=list(db.execute("SELECT revision,payload FROM events WHERE target_key='class_graph' AND revision<=18 ORDER BY revision"))
    require(len(events)==18 and not json.loads(events[-1][1])['state']['group_status'],'Expected legacy global-clear r18 fixture')
    before=fingerprint(STATE/'mask_reviews.sqlite3');sources=read(ROOT/'input_manifest.json')['source_fingerprints'];before_sources={p:fingerprint(PROJECT/p) for p 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
    errors=[];results=[]
    with tempfile.TemporaryDirectory(prefix='class-confirmation-persistence-',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);e=gallery.editor
            with closing(e.store.connect()) as db:
                require(db.execute('SELECT count(*) FROM events').fetchone()[0]==0,'Fresh temporary database required')
                db.execute('BEGIN IMMEDIATE')
                for revision,raw in events:db.execute('INSERT INTO events(target_key,revision,payload) VALUES (?,?,?)',('class_graph',revision,raw))
                db.execute('INSERT INTO reviews VALUES (?,?,?)',('class_graph',*events[-1]));db.commit()
            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:
                page.goto(base,wait_until='domcontentloaded');page.locator('#key').fill(key);page.locator('#loginButton').click();wait_value(page,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().revision===18')
                require(page.locator('#confirmedCards .card').count()==0,'Legacy bug fixture not reproduced')
                recovered=e.recover_confirmations(18)
                require(sorted(v['class_id'] for v in recovered['recovered_confirmations'].values())==[1,11,16,18],'Recovery includes wrong original class confirmations')
                require(sum(v['targets'] for v in recovered['recovered_confirmations'].values())==361,'Wrong recovered target scope')
                page.locator('#refresh').click();wait_value(page,'classCorrectionDiagnostics().revision===19')
                def confirmed(expected):
                    classes=page.locator('#confirmedCards .card').evaluate_all('(cards)=>cards.map(c=>Number(c.dataset.classId)).sort((a,b)=>a-b)')
                    require(classes==expected,'Confirmed shelf differs: '+str(classes))
                confirmed([1,11,16,18]);page.reload(wait_until='domcontentloaded');wait_value(page,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().revision===19');confirmed([1,11,16,18])
                page.locator('#filterStatus').select_option('confirm');require(page.locator('#groupSelect option').count()==4,'Confirmed filter lost history')
                require(len(context.request.get(base+'/api/review/export/confirmed.json').json()['records'])==361,'Recovered confirmation export differs')
                other=context.new_page();other.goto(base,wait_until='domcontentloaded');wait_value(other,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().revision===19')
                require(other.locator('#confirmedCards .card').count()==4,'New tab did not load durable confirmations');other.close()
                page.locator('#filterStatus').select_option('');page.locator('#filterK').select_option('12');graph=e.get()
                source=next(g['face_id'] for g in graph['groups'].values() if g['K']==12 and g['targets']>2)
                page.locator('#groupSelect').select_option(source);page.locator('#cards .card input').first.check();page.locator('#reviewer').fill('SYNTHETIC persistence only');page.locator('#note').fill('SYNTHETIC unrelated K12 split must preserve four classes');page.on('dialog',lambda dlg:dlg.accept());page.locator('#split').click()
                wait_value(page,'classCorrectionDiagnostics().revision===20&&!classCorrectionDiagnostics().saving');confirmed([1,11,16,18])
                page.reload(wait_until='domcontentloaded');wait_value(page,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().revision===20');confirmed([1,11,16,18])
                require(not e.history()[0]['invalidated_confirmations'],'Unrelated split invalidated existing confirmations')
                page.screenshot(path=str(OUT/f'four_classes_after_unrelated_split_reload_{width}.png'))
                page.locator('#filterK').select_option('8');one=next(g for g in e.get()['groups'].values() if g['proposed_class_id']==1)
                page.locator('#groupSelect').select_option(one['face_id']);page.locator('#cards .card input').first.check();page.locator('#note').fill('SYNTHETIC changed Class1 must invalidate only Class1');page.locator('#split').click()
                wait_value(page,'classCorrectionDiagnostics().revision===21&&!classCorrectionDiagnostics().saving');confirmed([11,16,18])
                require(e.history()[0]['invalidated_confirmations']==[one['face_id']],'Wrong scoped invalidation receipt')
                page.reload(wait_until='domcontentloaded');wait_value(page,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().revision===21');confirmed([11,16,18])
                require(len(e.export(True)['records'])==261 and not recoverable_confirmations(gallery.records,e.history(),e.get()['state']),'Changed Class1 incorrectly recoverable/exported')
                page.locator('details summary').click();page.locator('#history').select_option('19');page.locator('#note').fill('SYNTHETIC explicit restore recovered graph');page.locator('#restore').click()
                wait_value(page,'classCorrectionDiagnostics().revision===22&&!classCorrectionDiagnostics().saving');confirmed([1,11,16,18])
                require(len(e.history())==22,'Expected22 temp history events')
                with closing(e.store.connect()) as db:prefix=list(db.execute("SELECT revision,payload FROM events WHERE target_key='class_graph' AND revision<=18 ORDER BY revision"))
                require(prefix==events,'Original raw history changed')
                page.screenshot(path=str(OUT/f'confirmation_history_restore_{width}.png'))
                require(page.evaluate('document.documentElement.scrollWidth<=innerWidth'),'Horizontal overflow')
                results.append(dict(width=width,legacy_r18_global_clear_reproduced=True,recovered_classes=[1,11,16,18],recovered_targets=361,
                    refresh_reload_new_tab_preserve_confirmation=True,unrelated_K12_split_preserves_four_classes=True,changed_Class1_only_invalidated=True,
                    changed_Class1_not_recovered=True,original18_raw_events_preserved=True,explicit_history_restore_appends=True,temporary_new_events=4))
                print('Confirmation recovery/refresh/scoped invalidation passed',width,flush=True)
            finally:context.close();server.shutdown();server.server_close();worker.join()
        browser.close()
    require(before==fingerprint(STATE/'mask_reviews.sqlite3') and before_sources=={p:fingerprint(PROJECT/p) for p in sources} and not errors,'Real source/class store changed or browser errors')
    write(OUT/'acceptance.json',dict(state='passed_confirmation_persistence_recovery_actual_Chromium_temp_only',viewports=results,page_errors=errors,production_writes=0,
        manifest_sha256=digest(ROOT/'manifest.json'),ui_extension_sha256=gallery.ui_extension_sha256,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_writes=0))
        raise
