"""Read-only check that a target link reveals and locates its exact gallery card."""
import argparse
import json
import os
from pathlib import Path
import sys
import time
from urllib.parse import urlsplit,unquote

PROJECT=Path(__file__).resolve().parents[1]


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--target',default='f50f4c811248071f83eddf2b')
    parser.add_argument('--output',type=Path,default=PROJECT/'outputs/pallet_mask_quota_100_complete_deployment_v1')
    args=parser.parse_args();out=args.output.resolve()
    if not out.is_relative_to(PROJECT/'outputs'):raise ValueError('Expected validation outputs directory')
    path=out/'target_link_acceptance.json'
    if path.exists():raise ValueError('Preserve completed acceptance')
    config=json.loads((PROJECT/'configs/active_mask_gallery.json').read_text());root=PROJECT/config['directory']
    proposals={p['target_key']:p for p in map(json.loads,(root/'proposals.jsonl').read_text().splitlines())}
    if args.target not in proposals:raise ValueError('Target not published')
    base=json.loads((PROJECT/'outputs/pallet_mask_gallery_managed_v1/public_access.json').read_text())['public_url']
    url=base+f'/?revision={config["publication_version"]}&target={args.target}#target-{args.target}'
    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
    launch={};proxy_url=os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy')
    if proxy_url:
        p=urlsplit(proxy_url);launch['proxy']=dict(server=f'{p.scheme}://{p.hostname}:{p.port}',bypass='127.0.0.1,localhost')
        if p.username is not None:launch['proxy']['username']=unquote(p.username)
        if p.password is not None:launch['proxy']['password']=unquote(p.password)
    checks=[];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'],**launch)
        for width in (1400,390):
            ctx=browser.new_context(viewport=dict(width=width,height=900),is_mobile=width==390,has_touch=width==390)
            page=ctx.new_page();page.on('pageerror',lambda e:errors.append(str(e)))
            page.goto(url,wait_until='domcontentloaded',timeout=90000)
            deadline=time.monotonic()+90
            while time.monotonic()<deadline:
                if page.locator('.mg-linked-target').count():break
                time.sleep(.1)
            card=page.locator('#target-'+args.target)
            assert card.is_visible() and 'mg-linked-target' in card.get_attribute('class')
            assert not page.locator('#only-new').is_checked()
            assert page.locator('article:visible').count()==len(proposals)
            assert page.evaluate('maskGalleryDiagnostics().dirty') is False
            checks.append(dict(width=width,exact_target_visible=True,target_highlighted=True,no_edit_or_save=True))
            ctx.close()
        browser.close()
    if errors:raise AssertionError(errors)
    result=dict(state='passed',url=url,target=args.target,frame=proposals[args.target]['source']['frame_id'],checks=checks,production_annotation_writes=0)
    path.write_text(json.dumps(result,ensure_ascii=False,indent=2));print(json.dumps(result,ensure_ascii=False),flush=True)


if __name__=='__main__':main()
