"""Read-only public deployment checks for both joint review ports; never D or save."""
from contextlib import closing
from pathlib import Path
import hashlib
import json
import os
import sys

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.mask_model_training_data import read,write,jsonl,require
from pallet.cluster_targets import digest
from pallet.pallet_description_data import ROOT,sources_current
from pallet.pallet_description_review import SETS
from pallet.mask_template_refined import readonly
from reload_mask_taxonomy_keyboard_ui import state
from check_mask_taxonomy_complete_ui import idle
from check_mask_under50_ui import wait_value
from review_http_pool import ReadOnlyHTTP


def check():
    out=ROOT/'HANDOFF.json';require(not out.exists(),'Preserve previous joint publication handoff');require(sources_current(),'Source changed')
    key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip();receipts=[];before={};old_health=[]
    for mode,s in SETS.items():before[mode]=state(s['reviews']/'mask_reviews.sqlite3')
    for mode,s in SETS.items():
        runtime=read(s['managed']/'public_access.json');m=read(s['root']/'manifest.json');checked=[]
        layout=read(s['managed']/'layout_evidence/receipt.json')
        require(layout['state']=='passed_real_model_desktop_and_narrow_scroll_layout' and layout['manifest_sha256']==digest(s['root']/'manifest.json') and layout['production_annotation_POSTs']==0,'Actual readable desktop/narrow layout evidence required')
        with ReadOnlyHTTP(runtime['public_url'],attempts=3) as client:
            h=client.get('/healthz').json();require(h['publication_version']==s['namespace'] and h['targets']==m['request_count'] and h['joint_description'],'Wrong live joint service')
            client.get('/api/review/catalog',expected=401)
            for name in ('page.html','review.js','review.css','report-font.otf','classes.json','summary.json','quota_report.json','classification.csv','description_drafts.jsonl'):
                require(hashlib.sha256(client.get('/'+name).content).hexdigest()==m['public_assets'][name],'Wrong public resource bytes');checked.append(name)
            for name in ('/proposals.jsonl','/private/cycle2_reviews.sqlite3','/access_key.txt','/mask_reviews.sqlite3'):client.get(name,expected=404)
            client.login(key,gallery=True);catalog=client.get('/api/review/catalog').json();require(len(catalog['targets'])==m['request_count'],'Wrong live queue size')
            props=jsonl(s['root']/'proposals.jsonl')
            for p in props[:3]:
                d=client.get('/api/review/targets/'+p['target_key']).json();require(d['source_current'] and d['proposal']==p,'Wrong current description/keypoint source')
        receipts.append(dict(mode=mode,public_url=runtime['public_url'],local_url=runtime['local_url'],targets=m['request_count'],public_assets_verified=checked,manifest_sha256=digest(s['root']/'manifest.json')))
    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
    posts=[];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','--disable-features=VizDisplayCompositor'])
        context=browser.new_context(viewport=dict(width=1400,height=1000))
        def block(route):
            if route.request.method=='POST':posts.append(route.request.url);route.fulfill(status=405,content_type='application/json',body='{"error":"Read-only production acceptance"}')
            else:route.continue_()
        context.route('**/api/review/annotations/**',block)
        for receipt in receipts:
            page=context.new_page();page.on('pageerror',lambda e:errors.append(str(e)))
            try:
                page.goto(receipt['local_url'],wait_until='domcontentloaded');page.locator('#key').fill(key);page.locator('#loginButton').click();wait_value(page,'window.taxonomyDiagnostics&&taxonomyDiagnostics().loaded')
                page.locator('#classFilter').select_option('1');page.locator('#cards button').last.click();idle(page);i=page.evaluate('taxonomyDiagnostics().navigationIndex')
                require(page.locator('#descriptionText').input_value() and not page.locator('#descriptionConfirmed').is_checked(),'Description not loaded or auto-confirmed')
                if i>0:page.locator('#canvas').focus();page.keyboard.press('a');wait_value(page,'!taxonomyDiagnostics().opening&&taxonomyDiagnostics().navigationIndex==='+str(i-1));idle(page)
                page.screenshot(path=str(SETS[receipt['mode']]['managed']/'live_joint_editor.png'))
            finally:page.close()
        # Distinct cookie names allow both localhost ports to remain logged in together.
        for receipt in receipts:require(context.request.get(receipt['local_url']+'/api/review/catalog').status==200,'Sibling-port login invalidated auth cookie')
        context.close();browser.close()
    for mode,s in SETS.items():
        meta,events,_=before[mode];newmeta,new_events,_=state(s['reviews']/'mask_reviews.sqlite3');require(newmeta==meta and new_events[:len(events)]==events,'Original joint event history changed')
    require(not posts and not errors and sources_current(),'Annotation POST/browser error/source change during readonly deployment check')
    from urllib.request import urlopen
    for port in range(3406,3414):
        try:
            with urlopen(f'http://127.0.0.1:{port}/healthz',timeout=5) as response:h=json.load(response)
            old_health.append(dict(port=port,healthy=h.get('editing_enabled',False),targets=h.get('targets')))
        except OSError as e:old_health.append(dict(port=port,healthy=False,error=str(e)))
    quotas=read(ROOT/'release_quota_report.json');mask=read(ROOT/'run_v1_bfloat16/independent_branch/holdout_metrics.json');vlm=read(ROOT/'vlm_run_v2_format_repair/component_branch/holdout_metrics.json')
    write(out,dict(state='round3_mask_retraining_tiny_VLM_and_two_joint_review_queues_published',services=receipts,training_targets=5615,
        new_images=sum(q['selected_new_images'] for q in quotas.values()),new_image_gap=sum(q['gap'] for q in quotas.values()),per_class=quotas,
        mask_component_holdout=mask,vlm_component_holdout=vlm,vlm_structure_recovery_audit=read(ROOT/'vlm_run_v2_format_repair/structure_recovery_audit.json'),
        description_inference={mode:read(ROOT/f'description_inference_{mode}.json') for mode in SETS},observational_notes=14,missing_note_not_normal=True,
        no_new_blind_test_or_anomaly_generalization_claim=True,actual_public_GUI_verified=False,actual_local_GUI_A_only=True,production_annotation_POSTs=0,
        old_source_histories_unchanged=True,old_services_health=old_health,page_errors=errors,regressions_sha256=digest(ROOT/'regressions_330.xml'),code_sha256=digest(__file__)))
    print(dict(state='joint_description_services_public_readonly_verified',services=receipts,production_annotation_POSTs=0),flush=True)


if __name__=='__main__':check()
