"""Read-only local/public transport check; never submit a production assessment."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
from http.cookiejar import CookieJar
import json
from pathlib import Path
import sys
import time
from urllib.error import HTTPError, URLError
from urllib.request import Request, build_opener, HTTPCookieProcessor

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


def check(base,out,all_assets=False):
    out=Path(out).resolve()
    if out.exists():
        raise ValueError('Fresh transport evidence required')
    root=PROJECT/'outputs/pallet_mask_anomaly_human_review_package_v1'
    manifest=read(root/'manifest.json');jar=CookieJar();opener=build_opener(HTTPCookieProcessor(jar));transient=[];completed=[]
    def request(path,data=None,method=None):
        headers={}
        if data is not None:
            headers={'Content-Type':'application/json','X-Review-Request':'1','Origin':base}
        req=Request(base+path,data=canonical(data) if data is not None else None,headers=headers,method=method)
        for attempt in range(3):
            try:
                response=opener.open(req,timeout=20)
                break
            except HTTPError as error:
                response=error
                break
            except (URLError,TimeoutError,OSError) as error:
                transient.append(dict(path=path,attempt=attempt+1,error=str(error)))
                if attempt==2:
                    raise
                time.sleep(.3)
        with response:
            return response.status,{k.lower():v for k,v in response.headers.items()},response.read()
    checked=[];private_codes={}
    try:
        assert request('/api/catalog')[0]==401
        status,_,raw=request('/healthz');health=json.loads(raw)
        assert status==200 and health['targets']==455 and health['classes']==22 and health['labels_automatically_applied'] is False
        status,_,raw=request('/');assert status==200 and hashlib.sha256(raw).hexdigest()==manifest['public_assets']['index.html']
        secret=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
        assert request('/api/login',{'key':secret})[0]==200
        status,_,raw=request('/api/catalog');catalog=json.loads(raw)
        assert status==200 and len(catalog['targets'])==455 and len(catalog['classes'])==22
        completed.append('public_or_local_root_health_login_and_catalog')
        status,_,raw=request('/api/summary');before=json.loads(raw)
        assert status==200
        status,_,raw=request('/api/targets/'+catalog['queue'][0]);target=json.loads(raw)
        assert status==200 and target['package_sha256']==digest(root/'manifest.json')
        names=sorted(manifest['public_assets']) if all_assets else ['app.js','app.css','review-font.otf',
            target['target']['crop_url'][1:],catalog['references'][target['target']['same_class_reference_keys'][0]]['overlay_url'][1:]]
        def asset(name):
            status,headers,raw=request('/'+name)
            assert status==200 and hashlib.sha256(raw).hexdigest()==manifest['public_assets'][name],name
            assert 'frame-ancestors' in headers['content-security-policy']
            return name
        with ThreadPoolExecutor(max_workers=8 if all_assets else 2) as pool:
            checked=list(pool.map(asset,names))
        completed.append('selected_assets_hashed')
        for name in ('manifest.json','catalog.json','source_protection.json','reviews.sqlite3','access_key.txt',
            'private/source_catalog.jsonl','%2e%2e/configs/active_mask_gallery.json'):
            code=request('/'+name)[0];private_codes[name]=code
            allowed=(400,403,404) if name.startswith('%2e') else (404,)
            assert code in allowed, f'Private path was not rejected as expected: {name}: HTTP {code}'
        for method in ('PUT','DELETE','PATCH'):
            assert request('/',method=method)[0]==405
        assert request('/','POST is never a label save')[0]==405
        status,_,raw=request('/api/summary');after=json.loads(raw)
        assert status==200 and before==after,'Concurrent human save observed; do not attribute it to checker'
        value=dict(state='passed_readonly_transport_and_login_not_public_browser_or_Safari_certification',base_url=base,
            assets_verified=len(checked),all_assets_requested=all_assets,api_catalog_classes=22,api_queue_targets=455,
            authenticated_target_read=True,private_paths_not_served=True,non_review_asset_writes_rejected=True,
            production_assessment_posts=0,summary_unchanged=True,package_sha256=digest(root/'manifest.json'),
            transient_transport_errors_retried=transient,completed_stages=completed,
            private_path_rejection_status=private_codes,
            script_sha256=digest(__file__))
    except Exception as error:
        value=dict(state='failed_or_incomplete_transport_check',base_url=base,error=str(error),
            assets_verified_before_failure=len(checked),all_assets_requested=all_assets,production_assessment_posts=0,
            transient_transport_errors_retried=transient,completed_stages=completed,
            private_path_rejection_status=private_codes,
            script_sha256=digest(__file__))
        write(out,value);raise
    write(out,value);print(value,flush=True)


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('base');parser.add_argument('--out',type=Path,required=True);parser.add_argument('--all-assets',action='store_true')
    args=parser.parse_args();check(args.base.rstrip('/'),args.out,args.all_assets)
