"""Actual desktop/mobile class graph actions exclusively in temporary review stores."""
from contextlib import closing
from http.server import ThreadingHTTPServer
import csv
import io
import json
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_class_correction import ROOT
from pallet.mask_class_correction_review import ClassGallery,ClassHandler,transition
from pallet.mask_model_training_data import read,write,require
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'


def check():
    require(not (OUT/'ui_acceptance.json').exists(),'Preserve browser acceptance');OUT.mkdir(mode=0o700,exist_ok=True,parents=True)
    key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip();sources=read(ROOT/'input_manifest.json')['source_fingerprints'];before={p:fingerprint(PROJECT/p) for p in sources}
    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-correction-ui-',dir='/tmp/opencode') as scratch:
        class TestHandler(ClassHandler):
            def log_message(self,*args):pass
        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=ClassGallery(ROOT,Path(scratch)/str(width),key);server=ThreadingHTTPServer(('127.0.0.1',0),TestHandler);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}'
                ctx=browser.new_context(viewport=dict(width=width,height=height),is_mobile=width==390,has_touch=width==390);page=ctx.new_page();page.on('pageerror',lambda error:errors.append(str(error)))
                try:
                    page.goto(base,wait_until='domcontentloaded');wait_value(page,'window.classCorrectionDiagnostics');page.locator('#key').fill(key);page.locator('#loginButton').click()
                    wait_value(page,'classCorrectionDiagnostics().targets===2200')
                    assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
                    graph=ctx.request.get(base+'/api/review/graph').json();groups=graph['groups']
                    g=next(g for g in groups.values() if g['targets']>=3 and g['proposed_class_id'] is not None and any(
                        graph['state']['assignments'][t['target_key']]==g['face_id'] for cls in g['old_class_counts']
                        for t in [x for x in graph['targets'] if x['old_class_id']==int(cls) and x['actual_K']==g['K']][:2]));face=g['face_id'];k=g['K']
                    page.locator('#filterK').select_option(str(k));page.locator('#groupSelect').select_option(face)
                    wait_value(page,'classCorrectionDiagnostics().face==='+json.dumps(face));page.locator('#reviewer').fill('SYNTHETIC temporary browser only');page.locator('#note').fill('SYNTHETIC group confirmation; never real class decision')
                    if page.locator('#referenceCards').count():
                        wait_value(page,'document.querySelectorAll("#referenceCards .card").length>0')
                        assert page.evaluate('getComputedStyle(document.querySelector("#face pre")).fontFamily.includes("Review")')
                    upgraded=page.locator('#moveClass').count()>0
                    if upgraded:
                        assert page.locator('#confirmedCards .card').count()==0
                        card=page.locator('#cards .target-card').first;key_selected=card.get_attribute('data-key')
                        card.locator('img').first.click();assert page.evaluate('classCorrectionDiagnostics().selected')==[key_selected]
                        card.locator('img').nth(1).click();assert not page.evaluate('classCorrectionDiagnostics().selected')
                        card.locator('label').click();assert page.evaluate('classCorrectionDiagnostics().selected')==[key_selected]
                        card.locator('input').uncheck();assert not page.evaluate('classCorrectionDiagnostics().selected')
                        card.click(position=dict(x=4,y=4));assert page.evaluate('classCorrectionDiagnostics().selected')==[key_selected]
                        card.locator('button').click();assert page.locator('#detail').evaluate('(d)=>d.open') and page.evaluate('classCorrectionDiagnostics().selected')==[key_selected]
                        page.locator('#closeDetail').click();page.locator('#selectNone').click()
                        ref=page.locator('#referenceCards .target-card').first;refkey=ref.get_attribute('data-key');ref.locator('img').first.click()
                        assert page.evaluate('classCorrectionDiagnostics().selected')==[refkey]
                        assert page.locator('#cards .target-card[data-key="'+refkey+'"] input').is_checked()
                        ref.locator('button').click();assert page.evaluate('classCorrectionDiagnostics().selected')==[refkey]
                        page.locator('#closeDetail').click();page.locator('#selectNone').click()
                    page.screenshot(path=str(OUT/f'group_{width}.png'))
                    def failed(route):route.fulfill(status=503,content_type='application/json',body='{"error":"synthetic save failure"}')
                    page.route('**/api/review/action',failed);page.locator('#confirm').click();wait_value(page,'!classCorrectionDiagnostics().saving&&document.getElementById("status").textContent.includes("保存失败")')
                    assert page.evaluate('classCorrectionDiagnostics().revision')==0 and page.evaluate('classCorrectionDiagnostics().face')==face
                    assert page.evaluate('Object.keys(localStorage).some(k=>k.startsWith("class-correction-v1:"))')
                    page.screenshot(path=str(OUT/f'failure_keeps_draft_{width}.png'));page.unroute('**/api/review/action',failed)
                    page.locator('#confirm').click();wait_value(page,'classCorrectionDiagnostics().revision===1&&!classCorrectionDiagnostics().saving')
                    export=ctx.request.get(base+'/api/review/export/confirmed.json').json();assert len(export['records'])==g['targets'] and all(r['effective_label_is_human_confirmed'] for r in export['records'])
                    if upgraded:
                        assert page.locator('#confirmedCards .card').count()==1
                        assert page.locator('#confirmedCards .card').first.get_attribute('data-class-id')==str(g['proposed_class_id'])
                        otherK=next(x['K'] for x in groups.values() if x['K']!=k);page.locator('#filterK').select_option(str(otherK))
                        assert page.locator('#confirmedCards .card').count()==1
                        page.locator('#filterK').select_option(str(k));page.locator('#groupSelect').select_option(face)
                        page.locator('#cards').scroll_into_view_if_needed()
                        assert page.locator('#confirmedExamples').evaluate('(e)=>{const r=e.getBoundingClientRect();return r.top>=-1&&r.top<3&&r.bottom<innerHeight*.5}')
                        page.screenshot(path=str(OUT/f'confirmed_samples_sticky_{width}.png'))
                    download=ctx.request.get(base+'/api/review/export/confirmed.csv');assert download.status==200 and 'attachment;' in download.headers['content-disposition']
                    csvrows=list(csv.DictReader(io.StringIO(download.body().decode('utf-8-sig'))))
                    assert len(csvrows)==g['targets'] and all(r['effective_label_is_human_confirmed']=='True' for r in csvrows)
                    proposal_csv=ctx.request.get(base+'/api/review/export/proposals.csv')
                    assert proposal_csv.status==200 and len(list(csv.DictReader(io.StringIO(proposal_csv.body().decode('utf-8-sig')))))==2200
                    other=ctx.new_page();other.goto(base,wait_until='domcontentloaded');wait_value(other,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().revision===1');other.locator('#filterK').select_option(str(k));other.locator('#groupSelect').select_option(face)
                    other.locator('#reviewer').fill('SYNTHETIC stale tab');other.locator('#note').fill('SYNTHETIC stale must409')
                    page.locator('#note').fill('SYNTHETIC defer revision2');page.locator('#defer').click();wait_value(page,'classCorrectionDiagnostics().revision===2&&!classCorrectionDiagnostics().saving')
                    other.locator('#confirm').click();wait_value(other,'!classCorrectionDiagnostics().saving&&document.getElementById("status").textContent.includes("版本冲突")')
                    assert other.evaluate('classCorrectionDiagnostics().revision')==1;other.close()
                    page.locator('details summary').click();page.locator('#history').select_option('1');page.locator('#note').fill('SYNTHETIC restore appended');page.locator('#restore').click()
                    wait_value(page,'classCorrectionDiagnostics().revision===3&&!classCorrectionDiagnostics().saving')
                    assert len(ctx.request.get(base+'/api/review/export/confirmed.json').json()['records'])==g['targets']
                    graph=ctx.request.get(base+'/api/review/graph').json();wrong=next(x for x in graph['groups'].values() if x['K']!=k)
                    rejected=ctx.request.post(base+'/api/review/action',headers={'X-Review-Request':'1'},data=dict(binding=graph['binding'],expected_revision=3,reviewer='synthetic',note='crossK forbidden',action='merge',face_id=face,destination_face=wrong['face_id']))
                    assert rejected.status==400 and gallery.editor.store.get('class_graph')['revision']==3
                    page.locator('#cards .card input[type=checkbox]').first.check();selected_key=page.evaluate('classCorrectionDiagnostics().selected[0]');page.locator('#note').fill('SYNTHETIC split sameK subset');page.on('dialog',lambda dlg:dlg.accept());page.locator('#split').click()
                    wait_value(page,'classCorrectionDiagnostics().revision===4&&!classCorrectionDiagnostics().saving')
                    graph=ctx.request.get(base+'/api/review/graph').json();newface=graph['state']['assignments'][selected_key]
                    assert newface!=face and graph['groups'][newface]['K']==k and not graph['state']['group_status']
                    page.locator('#groupSelect').select_option(newface);page.locator('#destination').select_option(face);page.locator('#note').fill('SYNTHETIC merge back, reapprove required');page.locator('#merge').click()
                    wait_value(page,'classCorrectionDiagnostics().revision===5&&!classCorrectionDiagnostics().saving')
                    assert gallery.editor.store.get('class_graph')['state']['assignments'][selected_key]==face
                    assert len(gallery.editor.store.history('class_graph'))==5 and not ctx.request.get(base+'/api/review/export/confirmed.json').json()['records']
                    assert ctx.request.get(base+'/private/records.jsonl').status==404
                    final_revision=5
                    if upgraded:
                        page.locator('#groupSelect').select_option(face);page.locator('#note').fill('SYNTHETIC confirm destination for class move');page.locator('#confirm').click()
                        wait_value(page,'classCorrectionDiagnostics().revision===6&&!classCorrectionDiagnostics().saving')
                        graph=ctx.request.get(base+'/api/review/graph').json();cls=graph['groups'][face]['proposed_class_id'];choice=None
                        for t in graph['targets']:
                            source=graph['state']['assignments'][t['target_key']]
                            if source==face or t['actual_K']!=k or graph['groups'][source]['targets']<2:continue
                            try:transition(gallery.records,graph['state'],'move_class',dict(face_id=source,target_keys=[t['target_key']],destination_class_id=cls,note='test probe only'))
                            except ValueError:continue
                            choice=(source,t['target_key']);break
                        assert choice is not None
                        source,moving_key=choice;page.locator('#groupSelect').select_option(source)
                        page.locator('#cards .card[data-key="'+moving_key+'"] img').first.click();page.locator('#destinationClass').select_option(str(cls))
                        page.locator('#note').fill('SYNTHETIC selected targets directly into chosen Class')
                        page.route('**/api/review/action',failed);page.locator('#moveClass').click()
                        wait_value(page,'!classCorrectionDiagnostics().saving&&document.getElementById("status").textContent.includes("保存失败")')
                        assert page.evaluate('classCorrectionDiagnostics().revision')==6 and page.evaluate('classCorrectionDiagnostics().selected')==[moving_key]
                        page.unroute('**/api/review/action',failed);page.reload(wait_until='domcontentloaded')
                        wait_value(page,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().revision===6')
                        assert page.locator('#destinationClass').input_value()==str(cls) and page.evaluate('classCorrectionDiagnostics().selected')==[moving_key]
                        assert page.locator('#confirmedCards .card').count()==1
                        page.locator('#moveClass').click();wait_value(page,'classCorrectionDiagnostics().revision===7&&!classCorrectionDiagnostics().saving')
                        moved=ctx.request.get(base+'/api/review/graph').json();assert moved['state']['assignments'][moving_key]==face and moved['groups'][face]['proposed_class_id']==cls
                        assert not moved['state']['group_status'] and not page.locator('#confirmedCards .card').count()
                        assert gallery.editor.history()[0]['requested_destination_class_id']==cls
                        wrong=next(x for x in moved['groups'].values() if x['K']!=k and x['proposed_class_id'] is not None)
                        remaining=next(t['target_key'] for t in moved['targets'] if moved['state']['assignments'][t['target_key']]==source)
                        invalid=ctx.request.post(base+'/api/review/action',headers={'X-Review-Request':'1'},data=dict(binding=moved['binding'],expected_revision=7,reviewer='synthetic',note='crossK class move rejected',action='move_class',face_id=source,target_keys=[remaining],destination_class_id=wrong['proposed_class_id']))
                        assert invalid.status==400 and gallery.editor.store.get('class_graph')['revision']==7
                        page.screenshot(path=str(OUT/f'class_move_and_card_selection_{width}.png'));final_revision=7
                    gallery.editor.sources_current=lambda:False
                    assert ctx.request.get(base+'/api/review/export/confirmed.json').status==409
                    assert ctx.request.get(base+'/api/review/export/confirmed.csv').status==409
                    assert gallery.editor.store.get('class_graph')['revision']==final_revision
                    page.screenshot(path=str(OUT/f'after_split_merge_{width}.png'))
                    results.append(dict(width=width,height=height,initial_targets=2200,login_original_credential=True,no_horizontal_overflow=True,
                        failed_save_no_advance_draft_retained=True,actual_group_confirm=True,confirmed_overlay_only_export=True,stale_tab409=True,
                        history_restore_append_only=True,crossK_merge400_no_event=True,actual_subset_split=True,actual_group_merge=True,
                        changed_graph_invalidates_confirmations=True,csv_confirmed_and_proposals_verified=True,
                        source_change_blocks_confirmed_json_and_csv409=True,temporary_successful_saves=final_revision,
                        specified_class_move=upgraded,confirmed_samples_sticky_and_filter_independent=upgraded,
                        full_card_and_reference_selection_without_button_toggle=upgraded,class_move_failed_draft_and_reload_retained=upgraded))
                    print('Actual class correction fullflow passed',width,flush=True)
                finally:ctx.close();server.shutdown();server.server_close();worker.join()
            browser.close()
    after={p:fingerprint(PROJECT/p) for p in sources};require(before==after and not errors,'Real source changed or JS error')
    write(OUT/'ui_acceptance.json',dict(state='passed_actual_class_graph_browser_temp_only',viewports=results,page_errors=errors,
        source_fingerprints_before=before,source_fingerprints_after=after,production_writes=0,manifest_sha256=digest(ROOT/'manifest.json'),
        temporary_successes=sum(r['temporary_successful_saves'] for r in results),real_iPhone_Safari_tested=False,code_sha256=digest(__file__),
        ui_extension_sha256=gallery.ui_extension_sha256,review_implementation_sha256=digest(PROJECT/'pallet/mask_class_correction_review.py')))


if __name__=='__main__':
    import argparse
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--comparison',action='store_true');p.add_argument('--output',type=Path);a=p.parse_args()
    if a.output:OUT=a.output.resolve()
    elif a.comparison:OUT=OUT/'comparison_ui'
    try:check()
    except Exception as error:
        if OUT.exists() and not (OUT/'ui_failure.json').exists():
            secret=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
            write(OUT/'ui_failure.json',dict(state='failed_class_UI_not_deployed',error=str(error).replace(secret,'[redacted]'),production_writes=0))
        raise
