"""Headless desktop/mobile Chromium checks with all annotation requests blocked."""
from collections import Counter
import json
import os
from pathlib import Path
import sys
import time
from urllib.parse import urlsplit, unquote

PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))
from pallet.cluster_targets import digest
from pallet.mask_quality_recovery import fingerprint, POSE, GALLERY
from pallet.pose_review_geometry import canonical

TASKS = PROJECT/'outputs/pallet_mask_under50_requests_v1'
OUTPUT = PROJECT/'outputs/pallet_mask_under50_ui_acceptance_v3'


def read(path):
    return json.loads(Path(path).read_text())


def wait_value(page, expression, timeout=90):
    # Playwright 1.32's injected waitForFunction serializes functions with eval,
    # which the production CSP correctly forbids. Evaluate a read-only state
    # expression via DevTools instead; never add unsafe-eval or bypass CSP.
    deadline = time.monotonic()+timeout
    while time.monotonic() < deadline:
        if page.evaluate(expression):
            return
        time.sleep(.1)
    raise TimeoutError('UI state did not become ready: '+expression)


def check(base, output=OUTPUT):
    output = Path(output).resolve()
    if output.exists() or output.parent != PROJECT/'outputs':
        raise ValueError('Fresh UI evidence directory required')
    output.mkdir(mode=0o700)
    proposals = [json.loads(line) for line in (TASKS/'proposals.jsonl').read_text().splitlines()]
    counts = Counter(p['class_id'] for p in proposals)
    before = {name: fingerprint(path) for name, path in (('pose', POSE), ('gallery', GALLERY))}
    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
    settings = {}
    proxy_url = os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy')
    if proxy_url and urlsplit(base).hostname not in ('127.0.0.1', 'localhost'):
        proxy = urlsplit(proxy_url)
        settings['proxy'] = dict(server=f'{proxy.scheme}://{proxy.hostname}:{proxy.port}', bypass='localhost,127.0.0.1')
        if proxy.username:
            settings['proxy']['username'] = unquote(proxy.username)
        if proxy.password:
            settings['proxy']['password'] = unquote(proxy.password)
    errors = []; blocked = []; results = []
    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'], **settings)
        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 block(route):
                blocked.append(dict(path=urlsplit(route.request.url).path, viewport=width))
                route.fulfill(status=503, content_type='application/json', body='{"error":"Isolated read-only UI acceptance: production annotation write blocked"}')
            page.route('**/api/review/annotations/**', block)
            page.goto(base+'/template-requests/?batch=under50-v1', wait_until='domcontentloaded', timeout=90000)
            wait_value(page, 'window.maskGalleryDiagnostics && document.querySelectorAll(".mg-edit-button[data-key]").length==='+str(len(proposals)))
            page.evaluate('document.querySelectorAll("img").forEach(i=>i.loading="eager")')
            wait_value(page, 'Array.from(document.images).every(i=>i.complete&&i.naturalWidth>0)')
            assert page.locator('article:visible').count() == len(proposals)
            assert page.locator('#under50ScopeNote').is_visible()
            assert page.evaluate('document.documentElement.scrollWidth<=innerWidth')
            filters = []
            for cls in (11, 12, 16, 17, 19, 20):
                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]))
            page.locator('#request-filter').select_option('')
            page.screenshot(path=str(output/f'task_page_{width}.png'), full_page=True)
            editor_keys = []
            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 editor_keys:
                    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 initial['revision'] >= 0 and not initial['dirty']
                page.locator('#mgZoomIn').click(); page.locator('#mgZoomOut').click()
                assert page.evaluate('maskGalleryDiagnostics().polygon') == initial['polygon']
                assert page.evaluate('document.querySelector("#mgEditor").scrollWidth<=document.querySelector("#mgEditor").clientWidth+2')
                page.screenshot(path=str(output/f'editor_C{cls}_{width}.png'))
                editor_keys.append(key)
                page.locator('#mgClose').click()
                assert not page.evaluate('maskGalleryDiagnostics().open')
            # Exercise failed save / no-next and retained local draft entirely
            # in this disposable browser context. The route above never reaches
            # the production store; the HTTP checker separately confirms reads.
            page.locator('#request-filter').select_option('11')
            key = next(p['target_key'] for p in proposals if p['class_id'] == 11)
            page.locator(f'.mg-edit-button[data-key="{key}"]').click()
            wait_value(page, 'maskGalleryDiagnostics().imageStatus==="ready"&&!maskGalleryDiagnostics().loading')
            initial_revision = page.evaluate('maskGalleryDiagnostics().revision')
            page.locator('#mgNote').fill('Synthetic browser-only save-failure test; never submitted to production')
            page.locator('#mgNext').click()
            wait_value(page, 'maskGalleryDiagnostics().dirty&&!maskGalleryDiagnostics().saving&&document.getElementById("mgState").textContent.includes("未保存")')
            diagnostic = page.evaluate('maskGalleryDiagnostics()')
            assert diagnostic['target'] == key and diagnostic['revision'] == initial_revision and diagnostic['open']
            assert page.evaluate('Object.keys(localStorage).some(k=>k.startsWith("mask-gallery-v1:"))')
            results.append(dict(width=width, height=height, class_filters=filters, preview_count_loaded=len(proposals),
                editor_classes_tested=sorted(counts), no_horizontal_overflow=True,
                zoom_preserves_polygon=True, failed_save_does_not_advance=True, local_draft_preserved=True))
            context.close()
        browser.close()
    after = {name: fingerprint(path) for name, path in (('pose', POSE), ('gallery', GALLERY))}
    if errors:
        with (output/'failure.json').open('xb') as stream:
            stream.write(canonical(dict(state='blocked_page_error_or_concurrent_human_save', page_errors=errors,
                fingerprint_changes={name: before[name] != after[name] for name in before},
                browser_annotation_requests_intercepted=blocked, production_annotation_writes=0))+b'\n')
        raise ValueError('Page errors; preserve UI evidence for diagnosis')
    result = dict(state='passed_headless_chromium_not_real_iPhone', viewports=results,
        renderer_origin=base, rendered_over_public_tunnel=urlsplit(base).scheme == 'https',
        public_asset_transport_verification_is_separate=True,
        page_errors=errors, browser_annotation_requests_intercepted=blocked, production_annotation_writes=0,
        source_fingerprints_before=before, source_fingerprints_after=after,
        concurrent_store_changes_require_separate_event_provenance_audit=before != after,
        actual_saved_revisions_allowed_and_not_overwritten=True,
        task_verification_sha256=digest(TASKS/'verification.json'),
        code_sha256=digest(__file__), native_contour_accuracy_certified=False, real_iPhone_Safari_tested=False)
    with (output/'ui_acceptance.json').open('xb') as stream:
        stream.write(canonical(result)+b'\n')
    print(json.dumps(dict(state=result['state'], viewports=[r['width'] for r in results],
        production_annotation_writes=0, blocked_annotation_requests=len(blocked))), flush=True)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--base'); parser.add_argument('--output', type=Path, default=OUTPUT)
    args = parser.parse_args()
    check(args.base or 'http://127.0.0.1:3395', args.output)
