"""Read-only public acceptance for five new masks and assisted-seed provenance."""
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
from http.cookiejar import CookieJar
import hashlib
import json
import os
from pathlib import Path
import sqlite3
import sys
import time
from urllib.error import HTTPError
from urllib.request import Request,urlopen,build_opener,HTTPCookieProcessor

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.cluster_targets import digest,protected_snapshot
from pallet.mask_gallery import Gallery,active_directory
from pallet.pose_review_geometry import canonical

OUT=PROJECT/'outputs/pallet_mask_continuation_validation_v1'
ROOT=PROJECT/'outputs/pallet_mask_template_bulk_v5'


def main():
    receipt=OUT/'public_acceptance.json'
    if receipt.exists():raise ValueError('Existing publication evidence is immutable')
    services=json.loads((OUT/'services_before.json').read_text())
    gallery_state=PROJECT/'outputs/pallet_mask_gallery_managed_v1/public_access.json'
    state=json.loads(gallery_state.read_text());base=state['public_url'];gallery=Gallery(active_directory())
    h=json.load(urlopen(base+'/healthz',timeout=60));assert h['targets']==56 and h['publication_version']==3
    def verify_asset(item):
        route,(path,mime,sha)=item
        with urlopen(base+route+'?revision=3',timeout=60) as response:
            assert hashlib.sha256(response.read()).hexdigest()==sha and response.headers['Cache-Control']=='no-cache'
        return route
    with ThreadPoolExecutor(max_workers=4) as pool:assets=list(pool.map(verify_asset,gallery.assets.items()))
    for path in ('/reviews_snapshot.sqlite3','/auxiliary_seed.json','/proposals.jsonl','/registration_attempts.jsonl','/templates/',
                 '/cases/bf59aa3d7d604db6fe49debd.png'):
        try:urlopen(base+path,timeout=30);raise AssertionError('Internal asset exposed')
        except HTTPError as e:assert e.code==404
    pose=json.loads((PROJECT/'outputs/pallet_pose_review_managed_v1/public_access.json').read_text())
    opener=build_opener(HTTPCookieProcessor(CookieJar()))
    password=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    opener.open(Request(pose['public_url']+'/api/login',data=json.dumps(dict(key=password)).encode(),
        headers={'Content-Type':'application/json','X-Review-Request':'1'}),timeout=60).read()
    def read(path):return json.load(opener.open(pose['public_url']+path,timeout=60))
    new=[json.loads(s) for s in (ROOT/'new_proposals.jsonl').read_text().splitlines()]
    queue=read('/api/queue?state=mask_proposal');assert len(queue['keys'])==56
    auxiliary=0
    for p in new:
        d=read('/api/targets/'+p['target_key']);suggestion=d['mask_suggestion']
        assert suggestion and suggestion['version']==3 and suggestion['polygon']==p['polygon']
        assert suggestion['vertex_count']==p['vertex_count']
        if suggestion['template'].get('auxiliary_seed'):
            auxiliary+=1;assert suggestion['template']['human_polygon_revision'] is None
            assert not suggestion['template']['template_human_confirmed']
        assert not d['review'] or d['review']['polygon']!=p['polygon']
    assert auxiliary==2
    assert read('/api/targets/bf59aa3d7d604db6fe49debd')['mask_suggestion'] is None
    stats=read('/api/bootstrap')['stats'];assert stats['total']==12344 and stats['saved']==4733
    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
    checks=[]
    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'])
        for width in (1400,390):
            context=browser.new_context(viewport=dict(width=width,height=900),is_mobile=width==390,has_touch=width==390)
            page=context.new_page();errors=[];page.on('pageerror',lambda e:errors.append(str(e)))
            page.goto(base+'/?revision=3#new-batch',wait_until='domcontentloaded',timeout=60000)
            page.evaluate('document.fonts.ready');page.evaluate("document.querySelectorAll('img').forEach(x=>x.loading='eager')")
            deadline=time.monotonic()+120
            while not page.evaluate('Array.from(document.images).every(x=>x.complete&&x.naturalWidth>0)'):
                if time.monotonic()>deadline:raise AssertionError('Public image loading timeout')
                time.sleep(.2)
            assert page.locator('article').count()==56 and page.locator('article:visible').count()==5
            assert page.locator('#new-batch').is_visible() and page.evaluate('document.documentElement.scrollWidth<=innerWidth')
            page.screenshot(path=str(OUT/f'public_new_batch_{width}px.png'))
            page.locator('#filter').select_option('10');assert page.locator('article:visible').count()==2
            assert '非人工GT' in page.locator('article:visible').first.inner_text()
            page.locator('#onlyNew').uncheck();assert page.locator('article:visible').count()==6
            page.locator('#onlyNew').check();page.locator('article:visible').first.scroll_into_view_if_needed()
            page.screenshot(path=str(OUT/f'public_auxiliary_example_{width}px.png'))
            assert not errors
            checks.append(dict(width=width,new_only=5,total=56,Class10_new=2,Class10_total=6,all_images_loaded=True,
                auxiliary_seed_caption_explicit=True,no_overflow=True,page_errors=errors))
            context.close()
        browser.close()
    before=json.loads((OUT/'before_deployment.json').read_text())
    live=PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
    with closing(sqlite3.connect(live.resolve().as_uri()+'?mode=ro',uri=True)) as db:
        db.execute('ATTACH DATABASE ? AS frozen',((OUT/'reviews_before_maskcontinue.sqlite3').as_uri()+'?mode=ro',))
        assert db.execute('SELECT COUNT(*) FROM frozen.events f LEFT JOIN main.events m ON f.id=m.id WHERE m.payload IS NULL OR f.payload!=m.payload').fetchone()[0]==0
        assert db.execute('SELECT COUNT(*) FROM frozen.annotations f LEFT JOIN main.annotations m ON f.target_key=m.target_key WHERE m.payload IS NULL OR f.payload!=m.payload').fetchone()[0]==0
    for version in ('v2','v3'):
        for path,sha in json.loads((OUT/f'protected_{version}.json').read_text()).items():assert digest(PROJECT/path)==sha
    formal=Path(json.loads((PROJECT/'configs/active_formal_dataset.json').read_text())['dataset'])
    protected=json.loads((ROOT/'protected_formal_before.json').read_text());assert protected_snapshot(formal)==protected
    for name,old in services.items():
        now=json.loads((PROJECT/'outputs'/name/'supervisor.json').read_text())
        assert now['pid']==old['pid'] and now['tunnel']['pid']==old['tunnel']['pid']
        if name=='pallet_structure_review_managed_v1':assert now['app']['pid']==old['app']['pid']
    for name in ('supervisor.json','public_access.json'):
        path=gallery_state.with_name(name);value=json.loads(path.read_text())
        value.update(gallery='outputs/pallet_mask_template_bulk_v5/report_zh.html',gallery_config='configs/active_mask_gallery.json',publication_version=3)
        tmp=path.with_suffix('.continue.tmp');tmp.write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n');tmp.replace(path)
    result=dict(state='passed',publication_version=3,public_url=base+'/?revision=3#new-batch',new_candidates=5,total=56,
        old_candidates_preserved_byte_identical=51,auxiliary_seed_descendants=2,lower_rank_human_template_recoveries=3,
        public_assets_verified=len(assets),browser_checks=checks,all_new_online_suggestions_verified=True,
        old_human_payloads_preserved=4733,historical_events_preserved=10032,protected_formal_files_preserved=len(protected),
        all_previous_deliveries_unchanged=True,all_tunnels_and_supervisors_preserved=True,
        only_pose_and_gallery_application_children_reloaded=True,production_annotation_writes=0,human_confirmation_inferred=False,
        real_iPhone_Safari_tested=False)
    receipt.write_bytes(canonical(result)+b'\n');print(json.dumps(result),flush=True)


if __name__=='__main__':main()
