"""Actual integrated class service checks; only new temporary review epochs written."""
from contextlib import closing
from http.server import ThreadingHTTPServer
import csv
import io
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_note_integration import ROOT,STATE,CHECKS,IntegratedGallery,IntegratedHandler
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=CHECKS/'ui'


def check():
    require(not (OUT/'ui_acceptance.json').exists(),'Preserve integrated browser evidence');OUT.mkdir(mode=0o700,parents=True,exist_ok=True)
    inputs=read(ROOT/'input_manifest.json');before={p:fingerprint(PROJECT/p) for p in inputs['source_fingerprints']}
    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='integrated-class-review-',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=IntegratedGallery(ROOT,Path(scratch)/str(width),secret)
            class QuietHandler(IntegratedHandler):
                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 e:errors.append(str(e)))
            try:
                require(context.request.get(base+'/api/review/source-history').status==401,'Source history must require authentication')
                page.goto(base,wait_until='domcontentloaded');page.locator('#key').fill(secret);page.locator('#loginButton').click();wait_value(page,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().targets===2200')
                graph=context.request.get(base+'/api/review/graph').json();require(graph['revision']==1 and len(graph['groups'])==45 and page.locator('#confirmedCards .card').count()==45,'Confirmed groups were lost on integrated epoch initialization')
                byclass={g['proposed_class_id']:g for g in graph['groups'].values()}
                require(108 not in byclass and 124 not in byclass and byclass[14]['targets']==84 and byclass[115]['targets']==3,'Class moves/retirement not reflected')
                for cls,count,k in ((12,75,12),(85,11,12),(14,84,4),(115,3,8)):
                    page.locator('#filterK').select_option(str(k));page.locator('#groupSelect').select_option(byclass[cls]['face_id'])
                    require(page.locator('#cards .target-card').count()==count,'Current class membership count differs')
                    require(all(t['actual_K']==k for t in graph['targets'] if graph['state']['assignments'][t['target_key']]==byclass[cls]['face_id']),'Mixed-K group detected')
                    require('人工属性' in page.locator('#integratedAttributes').inner_text() and page.locator('#integratedOriginalNote').inner_text(),'Finished attributes/original notes not displayed')
                page.locator('#filterK').select_option('12');page.locator('#groupSelect').select_option(byclass[12]['face_id'])
                page.locator('#cards .card button').first.click();wait_value(page,'!document.getElementById("previousOverlay").hidden&&document.getElementById("previousOverlay").naturalWidth>0')
                require('实际12点' in page.locator('#detailTitle').inner_text(),'Updated actualK not shown in detail')
                page.screenshot(path=str(OUT/f'updated_K12_before_after_{width}.png'));page.locator('#closeDetail').click()
                for cls in (37,47):
                    page.locator('#filterK').select_option(str(byclass[cls]['K']));page.locator('#groupSelect').select_option(byclass[cls]['face_id'])
                    require('未解决注释1目标' in page.locator('#integratedAttributes').inner_text(),'Unsolved task not flagged')
                require(byclass[47]['K']==14 and byclass[37]['targets']==1,'Occlusion padded or unsaved target excluded')
                history=context.request.get(base+'/api/review/source-history').json();require(len(history['history'])==421 and history['read_only'],'Original421 history inaccessible')
                exported=context.request.get(base+'/api/review/export/confirmed.json').json();require(len(exported['records'])==2200 and sum(r['geometry_source']=='latest_integrated_note_revision' for r in exported['records'])==88,'Updated polygon source export incomplete')
                require(sum(r['original_note_save_action']=='draft' for r in exported['records'])==84 and sum(r['unresolved_note'] for r in exported['records'])==2,'Draft/unsolved provenance hidden')
                csv_response=context.request.get(base+'/api/review/export/confirmed.csv');require(csv_response.status==200 and len(list(csv.DictReader(io.StringIO(csv_response.body().decode('utf-8-sig')))))==2200,'Integrated CSV export broken')
                page.locator('#filterK').select_option('12');page.locator('#groupSelect').select_option(byclass[12]['face_id']);page.locator('#reviewer').fill('SYNTHETIC integrated temp only');page.locator('#note').fill('SYNTHETIC confirmation roundtrip')
                page.locator('#confirm').click();wait_value(page,'classCorrectionDiagnostics().revision===2&&!classCorrectionDiagnostics().saving')
                page.reload(wait_until='domcontentloaded');wait_value(page,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().revision===2');require(page.locator('#confirmedCards .card').count()==45,'Reload lost confirmations')
                other=context.new_page();other.goto(base,wait_until='domcontentloaded');wait_value(other,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().revision===2')
                other.locator('#filterK').select_option('12');other.locator('#groupSelect').select_option(byclass[12]['face_id']);other.locator('#reviewer').fill('SYNTHETIC stale');other.locator('#note').fill('stale must not overwrite')
                page.locator('#filterK').select_option('12');page.locator('#groupSelect').select_option(byclass[12]['face_id']);page.locator('#note').fill('SYNTHETIC defer one group');page.locator('#defer').click();wait_value(page,'classCorrectionDiagnostics().revision===3&&!classCorrectionDiagnostics().saving')
                require(page.locator('#confirmedCards .card').count()==44,'Only affected group should leave confirmed shelf')
                other.locator('#confirm').click();wait_value(other,'document.getElementById("status").textContent.includes("版本冲突")');other.close()
                require(gallery.editor.version()['revision']==3,'Stale tab overwrote integrated class review')
                page.locator('details summary').click();page.locator('#history').select_option('1');page.locator('#note').fill('SYNTHETIC restore initial integrated epoch');page.locator('#restore').click();wait_value(page,'classCorrectionDiagnostics().revision===4&&!classCorrectionDiagnostics().saving')
                require(page.locator('#confirmedCards .card').count()==45 and len(gallery.editor.history())==4,'History restore lost integrated data or failed append-only')
                require(context.request.get(base+'/private/records.jsonl').status==404 and context.request.get(base+'/private/source_class_reviews.sqlite3').status==404,'Private integrated source exposed')
                page.screenshot(path=str(OUT/f'integrated_review_roundtrip_{width}.png'))
                gallery.editor.sources_current=lambda:False
                require(context.request.get(base+'/api/review/export/confirmed.json').status==409,'New note source did not block stale integrated labels')
                require(page.evaluate('document.documentElement.scrollWidth<=innerWidth'),'Horizontal overflow')
                results.append(dict(width=width,targets=2200,groups=45,integrated88_latest_human_polygons=True,Class12_and85_K12=True,Class108_to14_and124_to115=True,
                    attributes_and_original421_history_preserved=True,before_after_overlay=True,unresolved37_and47_not_automatically_processed=True,
                    original_draft_actions_preserved_in_export=True,CSV2200=True,confirm_reload_and_stale409=True,history_restore_append_only=True,source_change409=True,temporary_successful_actions=3))
                print('Integrated class review actual browser passed',width,flush=True)
            finally:context.close();server.shutdown();server.server_close();worker.join()
        browser.close()
    require(before=={p:fingerprint(PROJECT/p) for p in inputs['source_fingerprints']} and not errors,'Original class/note/manual sources changed or browser error')
    write(OUT/'ui_acceptance.json',dict(state='passed_integrated_class_review_actual_Chromium_temp_only',viewports=results,page_errors=errors,production_writes=0,
        manifest_sha256=digest(ROOT/'manifest.json'),review_implementation_sha256=digest(PROJECT/'pallet/mask_class_note_integration.py'),
        temporary_successful_actions=6,temporary_initial_imports=2,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);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
