"""Inspect frozen/normalized layouts without changing either artifact or a live service."""
import json
import os
from pathlib import Path
import sys
from urllib.parse import unquote,urlsplit

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


def main():
    import argparse
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--directory',type=Path,default=PROJECT/'outputs/pallet_mask_remaining_continue_v1')
    parser.add_argument('--requests',type=Path,default=PROJECT/'outputs/pallet_mask_remaining_followup_requests_v2')
    parser.add_argument('--output',type=Path,default=PROJECT/'outputs/pallet_mask_remaining_continue_deployment_v1')
    args=parser.parse_args();root=args.directory.resolve();tasks=args.requests.resolve();out=args.output.resolve()
    if any(not p.is_relative_to(PROJECT/'outputs') for p in (root,tasks,out)):raise ValueError('Expected local output directories')
    result=out/'online_normalized_layout.json'
    if result.exists():raise ValueError('Preserve completed layout evidence')
    gallery=Gallery(root);html=root/'report_zh.html';before=digest(html)
    target_count=gallery.count;new_count=len((root/'new_proposals.jsonl').read_text().splitlines())
    task_count=json.loads((tasks/'manifest.json').read_text())['request_count']
    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=[];checks=[]
    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 mode,folder,raw in (('frozen',root,html.read_bytes()),('online_normalized',root,gallery.edited_page or html.read_bytes()),
                ('manual_tasks',tasks,(tasks/'report_zh.html').read_bytes())):
            for width in (1400,390):
                context=browser.new_context(viewport=dict(width=width,height=1000),is_mobile=width==390,has_touch=width==390)
                page=context.new_page();page.on('pageerror',lambda e:errors.append(str(e)))
                def asset(route):
                    name=unquote(urlsplit(route.request.url).path).lstrip('/') or 'report_zh.html'
                    path=(folder/name).resolve()
                    if not path.is_relative_to(folder) or not path.is_file():return route.fulfill(status=404,body='not found')
                    mime={'.html':'text/html; charset=utf-8','.png':'image/png','.otf':'font/otf','.txt':'text/plain; charset=utf-8'}.get(path.suffix)
                    if mime is None:return route.fulfill(status=404,body='not public')
                    route.fulfill(status=200,content_type=mime,body=raw if name=='report_zh.html' else path.read_bytes())
                page.route('http://pallet-layout.invalid/**',asset)
                page.goto('http://pallet-layout.invalid/',wait_until='load');page.evaluate('document.fonts.ready')
                dimension=page.evaluate('({viewport:innerWidth,document:document.documentElement.scrollWidth})')
                overflow=dimension['document']-dimension['viewport']
                if mode!='frozen':assert overflow<=0,(mode,width,dimension)
                assert page.locator('article').count()==(task_count if mode=='manual_tasks' else target_count)
                if mode=='online_normalized':
                    assert page.locator('#only-new').is_checked() and page.locator('article:visible').count()==new_count
                page.screenshot(path=str(out/f'layout_{mode}_{width}.png'))
                checks.append(dict(mode=mode,width=width,outer_overflow_pixels=overflow,article_count=page.locator('article').count()))
                context.close()
        browser.close()
    assert not errors and digest(html)==before
    value=dict(state='passed',checks=checks,frozen_html_sha256=before,frozen_html_unchanged=True,
        original_offline_overflow_reported_not_hidden=True,page_errors=errors,production_annotation_writes=0,
        real_iPhone_Safari_tested=False)
    result.write_bytes(canonical(value)+b'\n');print(json.dumps(value),flush=True)


if __name__=='__main__':main()
