"""Supplement-local desktop/mobile rendering; annotation requests always blocked."""
from collections import Counter
import json
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 scripts.check_mask_under50_ui import wait_value
from pallet.cluster_targets import digest
from pallet.pose_review_geometry import canonical


def check(batch, output):
    output = Path(output).resolve()
    if type(batch) is not int or batch < 4 or output.exists() or output.parent != PROJECT/'outputs':
        raise ValueError('Explicit batch and fresh local-UI output required')
    output.mkdir(mode=0o700)
    root = PROJECT/f'outputs/pallet_mask_under50_requests_v{batch}'
    manifest = json.loads((root/'manifest.json').read_text())
    proposals = [json.loads(line) for line in (root/'proposals.jsonl').read_text().splitlines()]
    counts = Counter(p['class_id'] for p in proposals)
    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, writes, results = [], [], []
    base = f'http://127.0.0.1:{3394+batch}'
    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'])
        for width, height in ((1400, 1000), (390, 844)):
            context = browser.new_context(viewport=dict(width=width, height=height), is_mobile=width == 390, has_touch=width == 390)
            page = context.new_page(); page.on('pageerror', lambda error: errors.append(str(error)))
            def deny(route):
                writes.append(dict(viewport=width, annotation_request_intercepted=True))
                route.fulfill(status=503, content_type='application/json', body='{"error":"Read-only UI acceptance"}')
            page.route('**/api/review/annotations/**', deny)
            page.goto(base+f'/template-requests/?batch=under50-v{batch}', wait_until='domcontentloaded', timeout=60000)
            wait_value(page, 'window.maskGalleryDiagnostics&&document.querySelectorAll("article[id^=target-]").length==='+str(len(proposals)))
            page.evaluate('document.querySelectorAll("img").forEach(i=>i.loading="eager")')
            wait_value(page, '[...document.images].every(i=>i.complete&&i.naturalWidth>0)')
            assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
            filters = []
            for cls in manifest['filter_classes']:
                page.locator('#request-filter').select_option(str(cls))
                assert page.locator('article:visible').count() == counts[cls]
                filters.append(dict(class_id=cls, visible=counts[cls]))
            if batch == 4:
                assert page.evaluate('!Array.from(document.getElementById("request-filter").options).some(o=>o.value==="20")')
            page.locator('#request-filter').select_option('')
            page.screenshot(path=str(output/f'task_page_{width}.png'), full_page=True)
            classes = []
            for cls in sorted(counts):
                key = next(p['target_key'] for p in proposals if p['class_id'] == cls)
                page.locator('#request-filter').select_option(str(cls))
                page.locator(f'.mg-edit-button[data-key="{key}"]').click()
                if not classes:
                    wait_value(page, 'document.getElementById("mgLogin").open')
                    page.locator('#mgAccessKey').fill((PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip())
                    page.locator('#mgLoginSubmit').click()
                wait_value(page, 'maskGalleryDiagnostics().open&&!maskGalleryDiagnostics().loading&&maskGalleryDiagnostics().imageStatus==="ready"&&maskGalleryDiagnostics().target==='+json.dumps(key))
                initial = page.evaluate('maskGalleryDiagnostics()')
                assert not initial['dirty']
                page.locator('#mgZoomIn').click(); page.locator('#mgZoomOut').click()
                assert page.evaluate('maskGalleryDiagnostics().polygon') == initial['polygon']
                assert page.evaluate('document.getElementById("mgEditor").scrollWidth<=document.getElementById("mgEditor").clientWidth+2')
                page.screenshot(path=str(output/f'editor_C{cls}_{width}.png'))
                page.locator('#mgClose').click(); classes.append(cls)
            results.append(dict(width=width, height=height, image_count=len(proposals), class_filters=filters,
                editor_classes_loaded=classes, zoom_preserves_polygon=True, no_horizontal_overflow=True))
            context.close()
        browser.close()
    if errors or writes:
        raise ValueError('Page errors or unexpected attempted save; keep evidence, never allow production write')
    result = dict(state='passed_local_headless_chromium_not_public_browser_or_real_Safari', batch=batch,
        viewports=results, page_errors=errors, annotation_requests_attempted=writes, production_annotation_requests_sent=0,
        task_verification_sha256=digest(root/'verification.json'), code_sha256=digest(__file__),
        save_failure_protection_unchanged_editor_covered_by_separate_regressions=True)
    with (output/'ui_acceptance.json').open('xb') as stream:
        stream.write(canonical(result)+b'\n')
    print(json.dumps(dict(state=result['state'], batch=batch, viewports=[1400, 390], request_count=len(proposals), production_annotation_requests_sent=0)), flush=True)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--batch', type=int, required=True); parser.add_argument('--output', type=Path, required=True)
    args = parser.parse_args(); check(args.batch, args.output)
