"""Read-only live verification of recovered confirmations and interface v4."""
from contextlib import closing
from collections import Counter
import hashlib
import json
import os
from pathlib import Path
import sys
import xml.etree.ElementTree as ET

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,NAMESPACE
from pallet.mask_model_training_data import read,write,require
from pallet.mask_quality_recovery import fingerprint
from pallet.mask_template_refined import readonly
from pallet.cluster_targets import digest
from audit_mask_class_correction import audit
from review_http_pool import ReadOnlyHTTP
from check_mask_under50_ui import wait_value

CHECKS=PROJECT/'outputs/pallet_mask_class_correction_checks_v1';OUT=CHECKS/'interface_v4'


def check():
    require(not (OUT/'HANDOFF.json').exists(),'Preserve confirmation release receipt')
    runtime=read(PROJECT/'outputs/pallet_mask_class_correction_managed_v1/public_access.json');extension=CHECKS/'ui_extension_v4'
    spec=read(extension/'manifest.json');ui=read(OUT/'ui/ui_acceptance.json');persistence=read(OUT/'persistence/acceptance.json');recovery=read(OUT/'recovery/recovery.json');plan=read(OUT/'recovery/plan.json')
    for proof in (ui,persistence):require(proof['manifest_sha256']==digest(ROOT/'manifest.json') and proof['ui_extension_sha256']==digest(extension/'manifest.json') and proof['review_implementation_sha256']==digest(PROJECT/'pallet/mask_class_correction_review.py') and not proof['page_errors'] and proof['production_writes']==0,'Acceptance binding differs')
    require(len(persistence['viewports'])==2 and all(v['refresh_reload_new_tab_preserve_confirmation'] and v['unrelated_K12_split_preserves_four_classes'] and v['changed_Class1_only_invalidated'] for v in persistence['viewports']),'Persistence regression proof missing')
    suites=ET.parse(OUT/'regressions.xml').getroot().findall('testsuite');tests=sum(int(s.attrib['tests']) for s in suites)
    require(tests>=150 and sum(int(s.attrib['errors'])+int(s.attrib['failures'])+int(s.attrib.get('skipped',0)) for s in suites)==0,'Regression failures')
    for p,h in read(ROOT/'input_manifest.json')['source_fingerprints'].items():require(fingerprint(PROJECT/p)==h,'Original human source changed')
    for name,h in read(ROOT/'manifest.json')['public_assets'].items():require(digest(ROOT/name)==h,'Frozen worklist asset changed')
    with closing(readonly(STATE/'mask_reviews.sqlite3')) as db:events=list(db.execute("SELECT revision,payload FROM events WHERE target_key='class_graph' ORDER BY revision"))
    require([hashlib.sha256(raw.encode()).hexdigest() for _,raw in events[:plan['expected_revision']]]==plan['old_raw_event_hashes'],'Original event prefix changed')
    recovered=json.loads(next(raw for rev,raw in events if rev==recovery['recovery_revision']))
    require(recovered['action']=='recover_confirmations' and recovered['recovered_confirmations']==plan['recoverable_confirmations'] and recovered['new_semantic_confirmations'] is False,'Wrong recovery event/provenance')
    expected={str(v['class_id']):v['targets'] for v in recovery['recovered_confirmations'].values()}
    require(expected=={'1':100,'11':99,'16':92,'18':70},'Unexpected recovery classes/target counts')
    secret=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    with ReadOnlyHTTP(runtime['public_url']) as client:
        require(client.get('/healthz').json()['service']==NAMESPACE,'Wrong live service')
        require(client.get('/').content==(extension/'page.html').read_bytes(),'Updated UI not deployed')
        for name,h in spec['public_assets'].items():require(hashlib.sha256(client.get('/review-ui/v4/'+name).content).hexdigest()==h,'Public interface asset differs')
        client.get('/api/review/graph',expected=401);client.get('/private/records.jsonl',expected=404);client.login(secret,gallery=True)
        graph=client.get('/api/review/graph').json();export=client.get('/api/review/export/confirmed.json').json()
        require(graph['source_current'] and graph['revision']==recovery['recovery_revision'],'Source changed or later human edits; review new state before final handoff')
        require(dict(Counter(str(r['corrected_class_id']) for r in export['records']))==expected,'Recovered confirmed export differs')
    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=[];before=fingerprint(STATE/'mask_reviews.sqlite3')
    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)):
            context=browser.new_context(viewport=dict(width=width,height=height),is_mobile=width==390,has_touch=width==390)
            context.route('**/api/review/action',lambda route:route.fulfill(status=599,body='Read-only production browser check'))
            page=context.new_page();page.on('pageerror',lambda error:errors.append(str(error)))
            try:
                page.goto(runtime['local_url'],wait_until='domcontentloaded');page.locator('#key').fill(secret);page.locator('#loginButton').click()
                wait_value(page,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().targets===2200')
                def assert_confirmed():
                    require(page.locator('#confirmedCards .card').evaluate_all('(xs)=>xs.map(x=>Number(x.dataset.classId)).sort((a,b)=>a-b)')==[1,11,16,18],'Live confirmed shelf lost information')
                    require(page.evaluate('classCorrectionDiagnostics().revision')==recovery['recovery_revision'],'Live revision changed')
                assert_confirmed();page.reload(wait_until='domcontentloaded');wait_value(page,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().targets===2200');assert_confirmed()
                page.locator('#refresh').click();wait_value(page,'document.getElementById("status").textContent.includes("已加载")');assert_confirmed()
                page.locator('#filterStatus').select_option('confirm');require(page.locator('#groupSelect option').count()==4,'Live confirmed filter differs')
                other=context.new_page();other.goto(runtime['local_url'],wait_until='domcontentloaded');wait_value(other,'window.classCorrectionDiagnostics&&classCorrectionDiagnostics().targets===2200')
                require(other.locator('#confirmedCards .card').count()==4,'New live browser tab lost confirmations');other.close()
                page.screenshot(path=str(OUT/f'live_confirmed_after_refresh_{width}.png'));require(page.evaluate('document.documentElement.scrollWidth<=innerWidth'),'Horizontal overflow')
                results.append(dict(width=width,confirmed_classes=[1,11,16,18],confirmed_targets=361,refresh_reload_new_tab_passed=True,production_decision_POST_blocked=True))
            finally:context.close()
        browser.close()
    require(before==fingerprint(STATE/'mask_reviews.sqlite3') and not errors,'Browser reads changed real graph or JS errors')
    old_services=[]
    for port in (3406,3407,3408,3409):
        with ReadOnlyHTTP(f'http://127.0.0.1:{port}') as client:
            h=client.get('/healthz').json();require(h['editing_enabled'],'Old service stopped');old_services.append(dict(port=port,targets=h['targets']))
    reload=read(OUT/'app_reload.json');require(reload['public_url']==runtime['public_url'] and reload['old_event_prefix_preserved'],'Original tunnel/history reload proof missing')
    value=dict(state='deployed_scoped_confirmation_persistence_and_recovered_original_human_decisions',public_url=runtime['public_url'],local_url=runtime['local_url'],
        cause='legacy_all_group_status_reset_on_any_merge_split_or_move_not_browser_refresh_or_history_deletion',
        fix='invalidate_only_exact_members_or_class_vote_evidence_changed; preserve_unaffected_decisions_and_tie_choices',
        recovered_classes=expected,recovered_targets=361,recovery_revision=recovery['recovery_revision'],original18_raw_events_preserved=True,
        recovery_is_append_only=True,new_semantic_confirmations=False,assignments_anchors_new_ids_unchanged_by_recovery=True,
        cpu_regressions=tests,actual_browser_checks=results,page_errors=errors,public_HTTPS_assets_and_authenticated_export_verified=True,
        manifest_sha256=digest(ROOT/'manifest.json'),ui_extension_sha256=digest(extension/'manifest.json'),review_implementation_sha256=digest(PROJECT/'pallet/mask_class_correction_review.py'),
        recovery_sha256=digest(OUT/'recovery/recovery.json'),persistence_acceptance_sha256=digest(OUT/'persistence/acceptance.json'),ui_acceptance_sha256=digest(OUT/'ui/ui_acceptance.json'),
        regressions_sha256=digest(OUT/'regressions.xml'),old_services_preserved=old_services,original_access_code_retained_not_disclosed=True,
        no_training_no_GT_no_other_target_propagation=True,temporary_Quick_Tunnel_URL=True,real_iPhone_Safari_tested=False,final_audit=audit(),code_sha256=digest(__file__))
    write(OUT/'HANDOFF.json',value);print({k:value[k] for k in ('state','public_url','recovered_classes','recovered_targets','recovery_revision','cpu_regressions')})


if __name__=='__main__':check()
