"""Read-only corrected gallery and proposal-sidecar rollout acceptance."""
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_boundary_validation_v1'
TARGET='ecb32bf169bd814b13791e4d'


def main():
    receipt=OUT/'public_acceptance.json'
    if receipt.exists():raise ValueError('Do not overwrite completed acceptance')
    before=json.loads((OUT/'before_deployment.json').read_text())
    gallery_state=PROJECT/'outputs/pallet_mask_gallery_managed_v1/public_access.json'
    access=json.loads(gallery_state.read_text());base=access['public_url'];root=active_directory();g=Gallery(root)
    for url in ('http://127.0.0.1:3393',base):
        h=json.load(urlopen(url+'/healthz',timeout=60));assert h['targets']==51 and h['publication_version']==2
    def fetch_asset(item):
        route,(file,mime,sha)=item
        with urlopen(base+route+'?revision=2',timeout=60) as response:
            assert hashlib.sha256(response.read()).hexdigest()==sha
            assert response.headers['Cache-Control']=='no-cache'
        return route
    with ThreadPoolExecutor(max_workers=4) as pool:assets=list(pool.map(fetch_asset,g.assets.items()))
    for path in ('/reviews_snapshot.sqlite3','/review_required.jsonl','/proposals.jsonl','/templates/','/cases/bf59aa3d7d604db6fe49debd.png'):
        try:urlopen(base+path,timeout=30);raise AssertionError('Nonpublic asset served')
        except HTTPError as e:assert e.code==404
    # The pose service reloads only the sidecar configuration, not its process.
    pose_access=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_access['public_url']+'/api/login',data=json.dumps(dict(key=password)).encode(),
        headers={'Content-Type':'application/json','X-Review-Request':'1'}),timeout=60).read()
    detail=json.load(opener.open(pose_access['public_url']+'/api/targets/'+TARGET,timeout=60))
    suggestion=detail['mask_suggestion'];assert suggestion and suggestion['version']==2 and len(suggestion['polygon'])==8
    assert abs(suggestion['polygon'][1][0]-259.98245)<.005 and abs(suggestion['polygon'][1][1]-186.64089)<.005
    withdrawn=json.load(opener.open(pose_access['public_url']+'/api/targets/bf59aa3d7d604db6fe49debd',timeout=60))
    assert withdrawn['mask_suggestion'] is None
    queue=json.load(opener.open(pose_access['public_url']+'/api/queue?state=mask_proposal',timeout=60))
    assert TARGET in queue['keys'] and len(queue['keys'])<=51
    with closing(sqlite3.connect((OUT/'reviews_before.sqlite3').as_uri()+'?mode=ro',uri=True)) as db:
        old_target=json.loads(db.execute('SELECT payload FROM annotations WHERE target_key=?',(TARGET,)).fetchone()[0])
    assert detail['review']==old_target
    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
    browsers=[]
    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=2#boundary-correction',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('Gallery images did not load')
                time.sleep(.2)
            assert page.locator('article').count()==51 and page.locator('#boundary-correction').is_visible()
            assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
            assert page.evaluate('document.fonts.check(\'16px PreviewSans\',\'顶点修正横梁\')')
            page.screenshot(path=str(OUT/f'public_gallery_correction_{width}px.png'))
            page.locator('#filter').select_option('10');assert page.locator('article:visible').count()==4
            page.locator('#target-'+TARGET).scroll_into_view_if_needed()
            page.screenshot(path=str(OUT/f'public_target_corrected_{width}px.png'))
            assert not errors
            browsers.append(dict(width=width,all_images_loaded=True,correction_notice_visible=True,class10_count=4,
                corrected_target_visible=True,no_overflow=True,page_errors=errors))
            context.close()
        browser.close()
    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.sqlite3').as_uri()+'?mode=ro',))
        changed=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]
        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 json.loads(db.execute('SELECT payload FROM annotations WHERE target_key=?',(TARGET,)).fetchone()[0])==old_target
    for path,sha in before['parent_files'].items():assert digest(PROJECT/path)==sha,path
    formal=Path(json.loads((PROJECT/'configs/active_formal_dataset.json').read_text())['dataset'])
    assert protected_snapshot(formal)==before['protected_formal']
    for name in ('outputs/pallet_pose_review_managed_v1/supervisor.json','outputs/pallet_structure_review_managed_v1/supervisor.json'):
        now=json.loads((PROJECT/name).read_text());old=before['services'][name]
        assert now['pid']==old['pid'] and now['app']['pid']==old['app']['pid'] and now['tunnel']['pid']==old['tunnel']['pid']
    prior=before['services']['outputs/pallet_mask_gallery_managed_v1/public_access.json']
    now=json.loads(gallery_state.read_text());assert now['pid']==prior['pid'] and now['tunnel']['pid']==prior['tunnel']['pid'] and now['public_url']==prior['public_url']
    # Synchronize content metadata after an app-only reload by the existing
    # supervisor; the active config and live /healthz remain content authority.
    for name in ('public_access.json','supervisor.json'):
        path=gallery_state.with_name(name);state=json.loads(path.read_text())
        state.update(gallery='outputs/pallet_mask_template_bulk_v3/report_zh.html',gallery_config='configs/active_mask_gallery.json',publication_version=2)
        tmp=path.with_suffix('.boundary.tmp');tmp.write_text(json.dumps(state,ensure_ascii=False,indent=2)+'\n');tmp.replace(path)
    result=dict(state='passed',public_url=base+'/?revision=2#boundary-correction',published_candidates=51,
        corrected_proposals=1,quarantined_proposals=1,unchanged_proposals=50,public_assets_verified=len(assets),
        browser_checks=browsers,online_suggestion_version=2,available_online_suggestions=len(queue['keys']),
        corrected_target_human_payload_unchanged=True,preexisting_payload_changes_since_backup=changed,
        historical_events_preserved=before['history_count'],formal_protected_files_preserved=len(before['protected_formal']),
        old_gallery_and_archives_preserved=True,annotation_services_not_restarted=True,
        gallery_tunnel_and_url_preserved=True,production_annotation_writes=0,real_iPhone_Safari_tested=False)
    receipt.write_bytes(canonical(result)+b'\n');print(json.dumps(result),flush=True)


if __name__=='__main__':main()
