"""Actual old-Class reuse and audit/export acceptance; all saves in temporary copies."""
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,STATE
from pallet.mask_class_correction_review import ClassGallery,ClassHandler,old_class_available
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_v5/old_class_reuse'


def check():
    require(not (OUT/'acceptance.json').exists(),'Preserve old-Class reuse acceptance');OUT.mkdir(mode=0o700,parents=True,exist_ok=True)
    before=fingerprint(STATE/'mask_reviews.sqlite3');sources=read(ROOT/'input_manifest.json')['source_fingerprints'];before_sources={p:fingerprint(PROJECT/p) for p in sources}
    secret=(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-reuse-old-ui-',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),secret);e=gallery.editor
            with closing(readonly(STATE/'mask_reviews.sqlite3')) as source:
                with closing(e.store.connect()) as dest:source.backup(dest)
            initial=e.get();base_revision=initial['revision'];choices=[(g,c) for g in initial['groups'].values() if not g['majority_anchors'] and g['targets']>1 for c in range(1,23) if old_class_available(gallery.records,initial['groups'],g['face_id'],c)]
            require(choices,'No actual unoccupied-old-Class/no-majority fixture');g,cls=choices[0];face=g['face_id'];count=g['targets']
            with closing(e.store.connect()) as db:prefix=list(db.execute("SELECT revision,payload FROM events WHERE target_key='class_graph' ORDER BY revision"))
            existing_confirmed=sorted(int(x['proposed_class_id']) for x in initial['groups'].values() if x['review_status']=='confirm')
            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(secret);page.locator('#loginButton').click();wait_value(page,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().targets===2200')
                page.locator('#filterK').select_option(str(g['K']));page.locator('#groupSelect').select_option(face)
                page.locator('#cards .target-card input').first.check();selected=page.evaluate('classCorrectionDiagnostics().selected')
                page.locator('#destinationClass').select_option(str(cls));require(page.locator('#destinationClass option:checked').get_attribute('data-kind')=='reuse_old_class','Unoccupied old Class not offered')
                require(not page.locator('#reuseOldClass').is_disabled() and page.locator('#moveClass').is_disabled(),'Whole-group reuse must be separate from moving selected targets')
                require('当前整组' in page.locator('#classActionInfo').inner_text() and '不是仅勾选' in page.locator('#classActionInfo').inner_text(),'Whole-group scope not explained')
                page.locator('#reviewer').fill('SYNTHETIC old-Class reuse only');page.locator('#note').fill('SYNTHETIC human whole-group assignment to vacant old Class, not retain')
                dialogs=[]
                def accept(dlg):dialogs.append(dlg.message);dlg.accept()
                page.on('dialog',accept)
                def failed(route):route.fulfill(status=503,content_type='application/json',body='{"error":"synthetic unavailable"}')
                page.route('**/api/review/action',failed);page.locator('#reuseOldClass').click()
                wait_value(page,'!classCorrectionDiagnostics().saving&&document.getElementById("status").textContent.includes("保存失败")')
                require(e.version()['revision']==base_revision and page.evaluate('classCorrectionDiagnostics().selected')==selected,'Failed reuse modified version/selection')
                page.unroute('**/api/review/action',failed);page.reload(wait_until='domcontentloaded');wait_value(page,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().targets===2200')
                require(page.locator('#destinationClass').input_value()==str(cls) and page.evaluate('classCorrectionDiagnostics().selected')==selected,'Old-Class reuse draft lost on reload')
                page.screenshot(path=str(OUT/f'old_class_reuse_ready_{width}.png'))
                page.locator('#reuseOldClass').click();wait_value(page,f'classCorrectionDiagnostics().revision==={base_revision+1}&&!classCorrectionDiagnostics().saving')
                moved=e.get();new=moved['groups'][face]
                require(new['proposed_class_id']==cls and new['decision']=='manual_old_class_assignment' and not new['majority_anchors'],'Manual assignment incorrectly presented as majority retain')
                require(new['majority_proposed_class_id']==g['majority_proposed_class_id'] and new['majority_support']==g['majority_support'],'Original majority evidence changed')
                require(moved['state']['assignments']==initial['state']['assignments'] and new['targets']==count and len(selected)<count,'Assignment must affect whole group label without moving member targets')
                require(new['review_status']=='pending' and moved['state']['group_status']=={f:s for f,s in initial['state']['group_status'].items() if f!=face},'Unrelated confirmations lost or manual change auto-confirmed')
                require(not any(r['face_group']==face for r in e.export(True)['records']),'Pending manual label leaked to confirmed export')
                require(any(str(count) in message and '不是仅处理勾选' in message for message in dialogs),'Whole group scope confirmation missing')
                proposals=e.export(False)['records'];manual=[r for r in proposals if r['face_group']==face]
                require(len(manual)==count and all(r['class_assignment_method']=='manual_old_class_assignment' and r['manual_class_id']==cls and r['corrected_class_id'] is None for r in manual),'Proposal assignment provenance missing')
                page.locator('#confirm').click();wait_value(page,f'classCorrectionDiagnostics().revision==={base_revision+2}&&!classCorrectionDiagnostics().saving')
                page.reload(wait_until='domcontentloaded');wait_value(page,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().targets===2200')
                confirmed=page.locator('#confirmedCards .card').evaluate_all('(xs)=>xs.map(x=>Number(x.dataset.classId)).sort((a,b)=>a-b)')
                require(confirmed==sorted(set(existing_confirmed+[cls])),'Manual Class confirmation not durable or previous confirmation lost')
                rows=[r for r in e.export(True)['records'] if r['face_group']==face];require(len(rows)==count and all(r['corrected_class_id']==cls and r['manual_class_id']==cls and r['class_assignment_method']=='manual_old_class_assignment' for r in rows),'Confirmed manual export labels/evidence differ')
                csv_response=context.request.get(base+'/api/review/export/confirmed.csv');csv_rows=list(csv.DictReader(io.StringIO(csv_response.body().decode('utf-8-sig'))))
                require(len([r for r in csv_rows if r['face_group']==face and r['manual_class_id']==str(cls) and r['class_assignment_method']=='manual_old_class_assignment'])==count,'CSV must expose manual provenance, not retain')
                page.screenshot(path=str(OUT/f'manual_old_class_confirmed_{width}.png'))
                version=base_revision+2;another=next(x for x in e.get()['groups'].values() if x['face_id']!=face and x['K']==g['K'] and not x['majority_anchors'])
                invalid=context.request.post(base+'/api/review/action',headers={'X-Review-Request':'1'},data=dict(binding=initial['binding'],expected_revision=version,reviewer='synthetic',note='occupied Class rejected',action='reuse_old_class',face_id=another['face_id'],destination_class_id=cls))
                require(invalid.status==400 and e.version()['revision']==version,'Occupied old Class reused by another group')
                other=context.new_page();other.goto(base,wait_until='domcontentloaded');wait_value(other,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().targets===2200')
                other.locator('#filterK').select_option(str(g['K']));other.locator('#groupSelect').select_option(face);other.locator('#reviewer').fill('SYNTHETIC stale');other.locator('#note').fill('SYNTHETIC stale confirm blocked')
                page.locator('#defer').click();wait_value(page,f'classCorrectionDiagnostics().revision==={base_revision+3}&&!classCorrectionDiagnostics().saving')
                other.locator('#confirm').click();wait_value(other,'document.getElementById("status").textContent.includes("版本冲突")');other.close()
                require(e.version()['revision']==base_revision+3,'Stale tab overwrote manual Class status')
                page.locator('details summary').click();page.locator('#history').select_option(str(base_revision));page.locator('#note').fill('SYNTHETIC restore pre-assignment graph');page.locator('#restore').click()
                wait_value(page,f'classCorrectionDiagnostics().revision==={base_revision+4}&&!classCorrectionDiagnostics().saving')
                restored=e.get();require(restored['state']==initial['state'] and restored['groups'][face]['proposed_class_id']==g['proposed_class_id'],'History restore did not undo manual whole-group label')
                with closing(e.store.connect()) as db:old=list(db.execute("SELECT revision,payload FROM events WHERE target_key='class_graph' AND revision<=? ORDER BY revision",(base_revision,)))
                require(old==prefix,'Original copied history changed');require(page.evaluate('document.documentElement.scrollWidth<=innerWidth'),'Horizontal overflow')
                results.append(dict(width=width,actual_K=g['K'],reused_old_class=cls,whole_group_targets=count,checked_targets=len(selected),no_majority_reuse=True,
                    whole_group_not_only_checkboxes=True,manual_not_retain_provenance=True,original_votes_and_members_unchanged=True,
                    unrelated_confirmations_preserved=True,explicit_confirmation_required_for_export=True,refresh_and_CSV_preserve_manual_label=True,
                    failed_save_and_draft_reload=True,occupied_Class400=True,stale409=True,history_restore_append_only=True,temporary_successful_saves=4))
                print('Manual whole-group old-Class reuse 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 database changed or JS errors')
    write(OUT/'acceptance.json',dict(state='passed_manual_old_class_whole_group_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
