"""Public byte/API checks and local GUI viewing; never submit production annotations."""
import hashlib
import os
from pathlib import Path
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,require,jsonl
from pallet.cluster_targets import digest
from pallet.pallet_description_review import SETS
from pallet.pallet_description_simple import ROOT,POLICY,initial_description
from pallet.pallet_description_data import sources_current
from reload_mask_taxonomy_keyboard_ui import state
from review_http_pool import ReadOnlyHTTP
from check_mask_under50_ui import wait_value
from check_mask_taxonomy_complete_ui import idle


def check():
    out=ROOT/'HANDOFF.json';require(not out.exists(),'Preserve previous delivery receipt');before={mode:state(s['reviews']/'mask_reviews.sqlite3') for mode,s in SETS.items()}
    key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip();services=[]
    for mode,s in SETS.items():
        runtime=read(s['managed']/'public_access.json');overlay=read(ROOT/mode/'manifest.json');original=read(ROOT/'before.json')['services'][mode]
        require(runtime['public_url']==original['runtime']['public_url'],'Original URL changed')
        require(digest(s['root']/'manifest.json')==original['manifest_sha256'] and digest(s['root']/'proposals.jsonl')==original['proposals_sha256'],'Frozen tasks changed')
        with ReadOnlyHTTP(runtime['public_url'],attempts=3) as client:
            require(client.get('/healthz').json()['description_policy']==POLICY,'Old public app still active')
            client.get('/api/review/catalog',expected=401)
            for name,h in overlay['assets'].items():require(hashlib.sha256(client.get('/'+name).content).hexdigest()==h,'Public overlay bytes differ: '+name)
            client.login(key,gallery=True);catalog=client.get('/api/review/catalog').json();require(catalog['description_policy']==POLICY,'Wrong catalog policy')
            require(sum(t['default_normal'] for t in catalog['targets'])==overlay['default_normal'],'Default-normal catalog counts differ')
            props=jsonl(s['root']/'proposals.jsonl');samples=[props[0]]+[p for p in props if p['human_note']]
            for p in samples:
                d=client.get('/api/review/targets/'+p['target_key']).json()
                require(d['proposal']==p and d['initial_description']==initial_description(p) and d['source_current'],'Initial description/data binding differs')
                if p['human_note']:require(d['initial_description']['observation']==p['human_note'],'Original human anomaly note lost')
        services.append(dict(mode=mode,public_url=runtime['public_url'],local_url=runtime['local_url'],port=s['port'],targets=overlay['targets'],default_normal=overlay['default_normal'],human_notes_preserved=sum(bool(p['human_note']) for p in props),overlay_manifest_sha256=digest(ROOT/mode/'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
    errors=[];posts=[]
    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):
            posts.append(route.request.url);route.fulfill(status=405,body='Readonly production check')
        context.route('**/api/review/annotations/**',block)
        for service in services:
            page=context.new_page();page.on('pageerror',lambda e:errors.append(str(e)))
            page.goto(service['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').first.click();idle(page)
            require(page.locator('#descriptionConfirmed').count()==0 and page.locator('#observationState').count()==0 and page.locator('#observationText').input_value()=='','Live UI still requires confirmation or unknown text')
            page.locator('#observationText').scroll_into_view_if_needed();page.screenshot(path=str(ROOT/service['mode']/'live_readonly.png'));page.close()
        for service in services:require(context.request.get(service['local_url']+'/api/review/catalog').status==200,'Sibling port login lost')
        context.close();browser.close()
    for mode,s in SETS.items():
        meta,events,_=before[mode];newmeta,new_events,current=state(s['reviews']/'mask_reviews.sqlite3')
        require(meta==newmeta and new_events[:len(events)]==events,'Historical events changed')
        require(not any('SYNTHETIC' in raw for _,_,_,raw in new_events),'Synthetic production annotation')
    require(not posts and not errors and sources_current(),'Readonly check wrote annotation or source/page error')
    write(out,dict(state='simplified_description_workflow_live_verified',policy=POLICY,services=services,production_annotation_POSTs=0,page_errors=errors,regressions_sha256=digest(ROOT/'regressions.xml'),actual_local_GUI=True,public_assets_and_authenticated_API_verified=True,actual_public_GUI=False,real_Safari_tested=False,old_labels_and_frozen_training_unchanged=True,history_and_draft_namespace_preserved=True,code_sha256=digest(__file__)))
    print(dict(state='simplified_description_workflow_live_verified',services=services,production_annotation_POSTs=0))


if __name__=='__main__':check()
