"""Read-only review package recomputation, without importing its generator."""
import argparse
from collections import Counter
from pathlib import Path
import re
import sys

import numpy as np
from PIL import Image, ImageDraw, ImageFont

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, jsonl, write, sha


def require(value,message):
    if not value:
        raise ValueError(message)


def verify(root,out):
    root,out=Path(root).resolve(),Path(out).resolve()
    require(not out.exists(), 'New verification evidence path required')
    manifest=read(root/'manifest.json');catalog=read(root/'catalog.json')
    report=PROJECT/'outputs/pallet_mask_annotation_anomalies_v2'
    full={r['target_key']:r for r in jsonl(report/'all_sources.jsonl')}
    model={r['target_key']:r for r in jsonl(report/'training_sources.jsonl')}
    desired={k for k,r in full.items() if r['flags']}|{k for k,r in model.items() if r['flags']}
    require(len(desired)==455 and set(catalog['targets'])==desired and set(catalog['queue'])==desired
        and len(catalog['queue'])==455,'Anomaly union/global unique target inventory differs')
    require(set(catalog['queue'][:23])=={k for k,r in model.items() if r['flags']},'Current294 priority scope differs')
    require(digest(root/'catalog.json')==manifest['catalog_sha256'] and manifest['automatic_label_application'] is False,
        'Frozen catalog or non-application binding differs')
    for name,expected in manifest['report_source_sha256'].items():
        require(digest(report/name)==expected,'Frozen diagnostic report differs')
    for name,expected in manifest['source_code_sha256'].items():
        require(digest(PROJECT/name)==expected,'Frozen implementation differs')
    assets=manifest['public_assets']
    expected_assets={'index.html','app.js','app.css','review-font.otf','FONT_LICENSE.txt'}|{
        f'{kind}/{key}.png' for key in catalog['references'] for kind in ('media','overlay','full')}
    require(set(assets)==expected_assets and len(assets)==1682,'Explicit public asset allowlist differs')
    for name,expected in assets.items():
        require(not (root/name).is_symlink() and (root/name).resolve().is_relative_to(root)
            and digest(root/name)==expected,'Frozen public asset hash/path differs')
    for key,t in catalog['targets'].items():
        r=full[key]
        require(t['class_id']==r['class_id'] and t['polygon']==r['polygon'] and t['vertices']==r['vertices']
            and t['source_revision']==r['source_revision'] and t['source_payload_sha256']==r['source_payload_sha256']
            and t['source_polygon_sha256']==sha(r['polygon']) and t['formal_split']==r['formal_split']
            and t['current_flags']==model.get(key,{}).get('flags',[]) and t['all_flags']==r['flags']
            and t['source_quality']==r['source_quality'],'Source polygon/class/split/revision/diagnostic changed')
        require(len(t['same_class_reference_keys'])>=2 and key not in t['same_class_reference_keys']
            and all(full[k]['class_id']==r['class_id'] for k in t['same_class_reference_keys']), 'Self/wrong-class reference')
    require({c['class_id'] for c in catalog['classes']}==set(range(1,23)) and len(catalog['classes'])==22,'Missing class atlas card')
    def distribution(values):
        return '、'.join(f'{k}点×{n}' for k,n in sorted(Counter(values).items()))
    for cls in catalog['classes']:
        require(cls['vertex_distribution_text']==distribution([r['vertices'] for r in full.values() if r['class_id']==cls['class_id']])
            and len(cls['reference_keys'])>=3 and all(full[k]['class_id']==cls['class_id'] for k in cls['reference_keys']),
            'Visual atlas source/distribution differs')
    # Reconstruct native pixels, crops, localization frames and polygon overlays.
    config=read(PROJECT/'configs/active_formal_dataset.json')
    formal=Path(config['dataset']) if 'dataset' in config else None
    if formal is None:
        from pallet.mask_quota_saved_extension import load_formal_evidence
        formal,_,_=load_formal_evidence(read(PROJECT/'outputs/pallet_mask_remaining_round5_v1/manifest.json'))
    if not formal.is_absolute():
        formal=PROJECT/formal
    font=ImageFont.truetype('/tmp/opencode/pallet_pose_design/NotoSansCJKsc-Regular.otf',11)
    for key,reference in catalog['references'].items():
        r=full[key];path=formal/r['native_image']
        require(digest(path)==reference['original_image_sha256'],'Original image hash differs')
        image=Image.open(path).convert('RGB');bounds=reference['crop_bounds'];crop=image.crop(tuple(bounds))
        require(np.array_equal(np.asarray(crop),np.asarray(Image.open(root/reference['crop_url'][1:]))),'Native display crop pixels differ')
        marked=image.copy();box=r['bbox'];ImageDraw.Draw(marked).rectangle((box['x'],box['y'],box['x']+box['width'],box['y']+box['height']),outline='#ffd36b',width=1)
        require(np.array_equal(np.asarray(marked),np.asarray(Image.open(root/reference['full_url'][1:]))),'Full-frame original box display differs')
        crop=crop.resize((crop.width*3,crop.height*3),Image.Resampling.NEAREST);draw=ImageDraw.Draw(crop)
        local=[((p[0]-bounds[0])*3,(p[1]-bounds[1])*3) for p in r['polygon']]
        draw.line(local+[local[0]],fill='#55d5ff',width=2)
        for index,point in enumerate(local,1):
            draw.text((point[0]+2,point[1]-12),str(index),font=font,fill='#ffe178',stroke_width=1,stroke_fill='black')
        require(np.array_equal(np.asarray(crop),np.asarray(Image.open(root/reference['overlay_url'][1:]))),'Saved polygon overlay/order differs')
    require(digest(root/'source_protection.json')==manifest['source_protection_sha256'],'Protection receipt changed')
    source=read(root/'source_protection.json')
    from pallet.mask_quota_saved_extension import file_inventory
    from pallet.mask_quality_recovery import fingerprint, POSE, GALLERY
    from pallet.cluster_targets import protected_snapshot
    before=source['before']
    require(before['configs']==file_inventory(PROJECT/'configs') and before['formal_metadata']==protected_snapshot(formal)
        and before['frozen294']==file_inventory(PROJECT/'outputs/pallet_mask_dataset_update_v1')
        and before['pose']==fingerprint(POSE) and before['gallery']==fingerprint(GALLERY)
        and before['nonconforming']==fingerprint(PROJECT/'outputs/pallet_mask_nonconforming_reviews_v1/mask_reviews.sqlite3'),
        'Protected data changed since package build; never silently incorporate new saves')
    value=dict(state='passed_readonly_recomputed_sources_images_and_protection_not_semantic_class_certification',
        package_sha256=digest(root/'manifest.json'),catalog_sha256=digest(root/'catalog.json'),targets=455,current_priority=23,
        classes=22,source_images_and_overlays_recomputed=len(catalog['references']),asset_hashes_verified=len(assets),
        source_classes_splits_polygons_and_point_order_preserved=True,formal_metadata_files_preserved=len(before['formal_metadata']),
        pose_gallery_nonconforming_histories_unchanged=True,frozen294_and_configs_unchanged=True,
        no_label_or_training_application=True,verifier_sha256=digest(__file__))
    write(out,value);print(value,flush=True)


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root',type=Path,default=PROJECT/'outputs/pallet_mask_anomaly_human_review_package_v1')
    parser.add_argument('--out',type=Path,default=PROJECT/'outputs/pallet_mask_anomaly_review_readonly_verification_v1.json')
    args=parser.parse_args();verify(args.root,args.out)
