"""HTTPS class-only review resources/authenticated read acceptance, no decision POST."""
from pathlib import Path
import csv
import io
import json
import hashlib
import sys

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.mask_class_correction import ROOT,STATE,NAMESPACE
from pallet.mask_model_training_data import read,write,require
from pallet.cluster_targets import digest
from scripts.review_http_pool import ReadOnlyHTTP

OUT=PROJECT/'outputs/pallet_mask_class_correction_checks_v1'


def check(output=None):
    path=Path(output) if output else OUT/'public_acceptance.json';require(not path.exists(),'Preserve public acceptance evidence')
    runtime=read(PROJECT/'outputs/pallet_mask_class_correction_managed_v1/public_access.json');m=read(ROOT/'manifest.json')
    client=ReadOnlyHTTP(runtime['public_url']);health=client.get('/healthz').json()
    require(health['service']==NAMESPACE and health['targets']==2200,'Wrong explicit endpoint')
    page=client.get('/').text;require('旧类及拟合入面型对照' in page and '/review-ui/comparison.js' in page,'Comparison UI not deployed')
    names=['review.js','report-font.otf','targets.json','face_groups.json'];groups=read(ROOT/'face_groups.json')
    for g in groups.values():
        key=g['representatives'][0];names.extend([f'crops/{key}.png',f'overlays/{key}.png'])
    samples=[]
    from concurrent.futures import ThreadPoolExecutor
    def asset(name):
        response=client.get('/'+name);h=hashlib.sha256(response.content).hexdigest();require(h==m['public_assets'][name],'Public asset differs: '+name);return dict(path=name,sha256=h)
    with ThreadPoolExecutor(max_workers=4) as pool:samples=list(pool.map(asset,names))
    extension=OUT/'ui_extension';js=client.get('/review-ui/comparison.js').content;require(hashlib.sha256(js).hexdigest()==read(extension/'manifest.json')['comparison_js_sha256'],'Comparison asset differs')
    for private in ('/private/records.jsonl','/input_manifest.json','/assignments.json','/proposed_mapping.jsonl'):client.get(private,expected=404)
    client.get('/api/review/graph',expected=401)
    key=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip();require(client.login(key,gallery=True).status_code==200,'Original credential login failed')
    graph=client.get('/api/review/graph').json();export=client.get('/api/review/export/confirmed.json').json()
    require(len(graph['targets'])==2200 and len(graph['groups'])==m['initial_candidate_groups'] and graph['source_current'],'Wrong source/graph scope')
    # The agent must not submit even a successful review decision here.
    require(graph['revision']==0 and not export['records'],'Unexpected class decision already present; do not overwrite')
    confirmed=client.get('/api/review/export/confirmed.csv');proposals=client.get('/api/review/export/proposals.csv')
    require('attachment;' in confirmed.headers.get('Content-Disposition','') and not list(csv.DictReader(io.StringIO(confirmed.content.decode('utf-8-sig')))),'Confirmed CSV must be empty initially')
    require(len(list(csv.DictReader(io.StringIO(proposals.content.decode('utf-8-sig')))))==2200,'Proposals CSV scope differs')
    receipt=dict(state='passed_public_class_graph_HTTPS_read_only_not_semantic_accuracy',public_url=runtime['public_url'],local_url=runtime['local_url'],
        manifest_sha256=digest(ROOT/'manifest.json'),public_assets_checked=samples,comparison_asset_checked=True,
        authenticated_2200_target_graph_read=True,confirmed_overlay_initially_empty=True,production_class_decision_POST_attempts=0,
        production_decisions_written=0,private_sources_not_exposed=True,temporary_url=True,real_iPhone_Safari_tested=False,code_sha256=digest(__file__),
        csv_confirmed_empty_and_proposals2200=True,review_implementation_sha256=digest(PROJECT/'pallet/mask_class_correction_review.py'))
    write(path,receipt);client.close();print(dict(state=receipt['state'],assets=len(samples),public_url=runtime['public_url']),flush=True)


if __name__=='__main__':
    import argparse
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--output',type=Path);a=p.parse_args();check(a.output)
