"""Public gallery asset hashes, sensitive-path rejection and desktop/mobile UX."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
import os
from pathlib import Path
import sys
import time
from urllib.error import HTTPError
from urllib.request import Request,urlopen

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


def main():
    state=PROJECT/'outputs/pallet_mask_gallery_managed_v1';path=state/'public_verification.json'
    if path.exists():raise ValueError('Do not overwrite publication evidence')
    before=json.loads((state/'before_publication.json').read_text())
    access=json.loads((state/'public_access.json').read_text());base=access['public_url']
    gallery=Gallery(PROJECT/'outputs/pallet_mask_template_bulk_v2')
    assert json.load(urlopen(base+'/healthz',timeout=45))['targets']==52
    def check_asset(item):
        route,(file,mime,sha)=item
        with urlopen(base+route,timeout=60) as response:
            assert hashlib.sha256(response.read()).hexdigest()==sha,route
            assert response.headers.get('X-Content-Type-Options')=='nosniff'
            return route
    with ThreadPoolExecutor(max_workers=4) as pool:checked=list(pool.map(check_asset,gallery.assets.items()))
    rejected=[]
    for route in ('/reviews_snapshot.sqlite3','/reviews_snapshot.sqlite3-wal','/access_key.txt','/proposals.jsonl',
                  '/templates/','/cases/','/../configs/active_mask_template_proposals.json','/api/annotations/test'):
        try:urlopen(base+route,timeout=30);raise AssertionError('Exposed path '+route)
        except HTTPError as exc:
            # The public edge rejects raw parent-directory URLs before they
            # reach our allowlist. Both layers must deny access, not return data.
            assert exc.code in ((400,403,404) if '/../' in route else (404,)),(route,exc.code)
            rejected.append(dict(path=route,status=exc.code))
    try:urlopen(Request(base+'/',method='POST',data=b'test'),timeout=30);raise AssertionError('Writable gallery')
    except HTTPError as exc:assert exc.code==405
    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=[];errors=[]
    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();page.on('pageerror',lambda e:errors.append(str(e)))
            page.goto(base+'/',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 gallery images did not load')
                time.sleep(.2)
            assert page.locator('article').count()==52
            assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
            assert page.evaluate('document.fonts.check(\'16px PreviewSans\',\'批量掩膜候选\')')
            page.locator('#filter').select_option('15');assert page.locator('article:visible').count()==26
            page.screenshot(path=str(state/f'public_{width}px.png'))
            assert not errors
            checks.append(dict(viewport=width,all_52_images_loaded=True,Class15_filter_count=26,
                no_overflow=True,Chinese_font_loaded=True,page_errors=errors[:]))
            context.close()
        browser.close()
    for file,sha in before['assets'].items():assert digest(PROJECT/file)==sha,file
    for name,old in before['annotation_services'].items():
        now=json.loads((PROJECT/'outputs'/name/'supervisor.json').read_text())
        for field in ('pid','process_identity'):assert now[field]==old[field]
        assert now['app']['pid']==old['app']['pid'] and now['tunnel']['pid']==old['tunnel']['pid']
    for port in (3389,3390):assert json.load(urlopen(f'http://127.0.0.1:{port}/healthz',timeout=10))['status']=='ok'
    result=dict(state='passed',public_url=base,read_only=True,authentication_required=False,
        verified_public_asset_count=len(checked),rejected_private_paths=rejected,mutation_method_rejected=True,
        browser_checks=checks,source_gallery_files_unchanged=True,annotation_services_not_restarted=True,
        annotation_database_writes=0,temporary_quick_tunnel=True,boot_autostart_configured=False)
    path.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n');print(json.dumps(result,ensure_ascii=False),flush=True)


if __name__=='__main__':main()
