"""Freeze an anomaly-review queue plus22 visual class cards; no label edits."""
from collections import Counter, defaultdict
import math
from pathlib import Path
import shutil
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, protected_snapshot
from pallet.mask_quality_recovery import fingerprint, POSE, GALLERY
from pallet.mask_model_training_data import read, jsonl, write, sha
from pallet.mask_quota_saved_extension import file_inventory, load_formal_evidence
from scripts.audit_mask_annotation_anomalies import feature_index
from scripts.build_mask_remaining_direct_requests import build_font

REPORT = PROJECT/'outputs/pallet_mask_annotation_anomalies_v2'
OUT = PROJECT/'outputs/pallet_mask_anomaly_human_review_package_v1'
ASSETS = PROJECT/'pallet/assets/anomaly_review'


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


def distribution_text(counts):
    return '、'.join(f'{k}点×{n}' for k, n in sorted(counts.items(), key=lambda item: int(item[0])))


def build(out=OUT):
    OUT = Path(out).resolve()
    require(OUT.is_relative_to(PROJECT/'outputs') and OUT.name.startswith('pallet_mask_anomaly_human_review_package_v'),
        'Use a fresh versioned anomaly-review package under outputs')
    require(not OUT.exists(), 'Fresh immutable human-review package required')
    report_files = file_inventory(REPORT)
    handoff = read(REPORT/'FINAL_HANDOFF.json')
    require(handoff['state'] == 'completed_verified_readonly_diagnosis_not_dataset_correction'
        and handoff['readonly_verification_sha256'] == digest(REPORT/'readonly_verification.json'), 'Verified anomaly source required')
    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')}
    all_candidates = {k for k, r in full.items() if r['flags']}; current_candidates = {k for k, r in model.items() if r['flags']}
    keys = all_candidates | current_candidates
    require(len(keys) == 455 and len(current_candidates) == 23 and len(full) == 1559 and len(model) == 294, 'Frozen anomaly inventory changed')
    formal, rows, evidence = load_formal_evidence(read(PROJECT/'outputs/pallet_mask_remaining_round5_v1/manifest.json'))
    def protection():
        return dict(configs=file_inventory(PROJECT/'configs'), formal_metadata=protected_snapshot(formal),
            frozen294=file_inventory(PROJECT/'outputs/pallet_mask_dataset_update_v1'),
            pose=fingerprint(POSE), gallery=fingerprint(GALLERY),
            nonconforming=fingerprint(PROJECT/'outputs/pallet_mask_nonconforming_reviews_v1/mask_reviews.sqlite3'))
    before = protection()
    features = feature_index(rows); stats = read(REPORT/'class_statistics.json'); by_class = defaultdict(list)
    for r in full.values():
        by_class[r['class_id']].append(r)
    classes = []; needed = set(keys); major = {}
    for cls in range(1, 23):
        values = by_class[cls]; center = values[0]['class_references']; selected = []
        def add(key):
            if key not in selected and full[key]['class_id'] == cls:
                selected.append(key)
        add(center['main_target_key']); add(center['group_balanced_target_key'])
        for key in center['representative_keys']:
            add(key)
        counts = Counter(r['vertices'] for r in values)
        for count, n in sorted(counts.items(), key=lambda item: -item[1]):
            if n >= .20*len(values):
                candidates = [r for r in values if r['vertices'] == count]
                add(min(candidates, key=lambda r: (r['appearance']['within_class_distance_to_medoid'], r['target_key']))['target_key'])
        selected = selected[:6]; needed.update(selected); major[cls] = center['main_target_key']
        s = stats['all_saved'][str(cls)]; ms = stats['current_model'].get(str(cls))
        structure = sorted(s['structures'], key=lambda name: -s['structures'][name])[:2]
        classes.append(dict(class_id=cls, reference_keys=selected, vertex_distribution_text=distribution_text(s['vertex_count_distribution']),
            model_vertex_distribution_text=distribution_text(ms['vertex_count_distribution']) if ms else '未纳入当前294份',
            short_description='统计候选结构：'+' / '.join(structure)+'；不是已确认类定义。',
            caution='同类可能含不同观察面与范围惯例，请结合多图比较；不能按多数点数强改标签。',
            count=s['n'], acquisition_groups=s['acquisition_groups']))
    observations = {r['target_key']: r['finding'] for r in read(REPORT/'visual_review.json')['observations']}
    targets = {}
    for key in sorted(keys):
        r = full[key]; cls = r['class_id']; current = model.get(key); row = rows[key]
        use = current if key in current_candidates else r
        preferred = []
        def add_reference(candidate, role):
            if candidate != key and candidate not in [k for k, _ in preferred]:
                preferred.append((candidate, role))
        add_reference(use['class_references']['main_target_key'], '当前294内同类主要参考' if key in current_candidates else '全量同类主要参考（不是标准答案）')
        add_reference(use['class_references']['group_balanced_target_key'], '按采集组均衡的同类参考')
        similar = [v for v in by_class[cls] if v['target_key'] != key and v['policy_id'] == r['policy_id'] and v['surface'] == r['surface']]
        if similar:
            best = min(similar, key=lambda v: (float(np.linalg.norm(features[key]-features[v['target_key']])), v['target_key']))
            add_reference(best['target_key'], '同策略 / 候选观察面的不同样本（候选面未确认）')
        for k in use['class_references']['representative_keys']:
            add_reference(k, '另一个采集组 / 观察例')
        if len(preferred) < 3:
            for value in sorted(by_class[cls], key=lambda value: (value['group_id'] == r['group_id'], float(np.linalg.norm(features[key]-features[value['target_key']])), value['target_key'])):
                add_reference(value['target_key'], '同类补充参考，不代表语义已确认')
                if len(preferred) >= 3:
                    break
        preferred = preferred[:3]; needed.update(k for k, _ in preferred)
        alternatives = sorted((float(np.linalg.norm(features[key]-features[major[c]])), c) for c in range(1, 23) if c != cls)[:3]
        targets[key] = dict(target_key=key, class_id=cls, vertices=r['vertices'], polygon=r['polygon'], original_bbox=row['bbox'],
            formal_split=row['split'], source_size=row['size'], in_model_dataset=key in model,
            development_split=current['development_split'] if current else None, current_model_anomaly=key in current_candidates,
            current_flags=current['flags'] if current else [], all_flags=r['flags'], source_quality=r['source_quality'],
            source_revision=r['source_revision'], source_payload_sha256=r['source_payload_sha256'], source_polygon_sha256=sha(r['polygon']),
            image_label=row['frame_id'], same_class_reference_keys=[k for k, _ in preferred],
            reference_roles=dict(preferred), alternative_class_ids=[c for _, c in alternatives],
            visual_observation=observations.get(key), source_audit_scope='frozen1559/current294; subsequent human changes are not applied here',
            review_priority=max(r['review_priority'], current['review_priority'] if current else 0))
    OUT.mkdir(mode=0o700)
    for folder in ('media', 'full', 'overlay'):
        (OUT/folder).mkdir()
    references = {}; font = ImageFont.truetype('/tmp/opencode/pallet_pose_design/NotoSansCJKsc-Regular.otf', 11)
    for key in sorted(needed):
        r = full[key]; row = rows[key]; box = row['bbox']; points = r['polygon']; image = Image.fromarray(evidence.image(row['frame_id'])).convert('RGB')
        # Display-only crop may contain the entire saved polygon. This is not
        # the model's ROI and is never exported into its dataset.
        xs = [p[0] for p in points]+[box['x'], box['x']+box['width']]; ys = [p[1] for p in points]+[box['y'], box['y']+box['height']]
        bounds = [max(0, math.floor(min(xs)-max(8,.08*box['width']))), max(0, math.floor(min(ys)-max(8,.2*box['height']))),
            min(row['size'][0], math.ceil(max(xs)+max(8,.08*box['width']))), min(row['size'][1], math.ceil(max(ys)+max(8,.2*box['height'])))]
        image.crop(tuple(bounds)).save(OUT/'media'/f'{key}.png')
        marked = image.copy(); d = ImageDraw.Draw(marked); d.rectangle((box['x'],box['y'],box['x']+box['width'],box['y']+box['height']), outline='#ffd36b', width=1)
        marked.save(OUT/'full'/f'{key}.png')
        scale = 3; cropped = image.crop(tuple(bounds)); cropped = cropped.resize((cropped.width*scale, cropped.height*scale), Image.Resampling.NEAREST)
        d = ImageDraw.Draw(cropped); local = [((p[0]-bounds[0])*scale,(p[1]-bounds[1])*scale) for p in points]
        d.line(local+[local[0]], fill='#55d5ff', width=2)
        for index, point in enumerate(local, 1):
            d.text((point[0]+2, point[1]-12), str(index), font=font, fill='#ffe178', stroke_width=1, stroke_fill='black')
        cropped.save(OUT/'overlay'/f'{key}.png')
        references[key] = dict(target_key=key, class_id=r['class_id'], vertices=r['vertices'], formal_split=row['split'], source_quality=r['source_quality'],
            surface_label=r['surface'], structure_label=r['structure'], crop_url=f'/media/{key}.png', full_url=f'/full/{key}.png',
            overlay_url=f'/overlay/{key}.png', crop_bounds=bounds, original_image_sha256=digest(formal/row['image']))
        if key in targets:
            targets[key].update(crop_bounds=bounds, crop_url=f'/media/{key}.png', full_url=f'/full/{key}.png', overlay_url=f'/overlay/{key}.png')
    queue = sorted(keys, key=lambda k: (k not in current_candidates, -targets[k]['review_priority'], targets[k]['class_id'], k))
    catalog = dict(schema='anomaly_review_visual_catalog_v1', classes=classes, references=references, targets=targets, queue=queue,
        references_are_not_human_confirmed_class_definitions=True, same_source_polygon_order_preserved=True,
        diagnostics_are_candidates_not_confirmed_errors=True)
    write(OUT/'catalog.json', catalog)
    for name in ('index.html','app.css','app.js'):
        shutil.copyfile(ASSETS/name, OUT/name)
    build_font(OUT, (OUT/'index.html').read_text()+(OUT/'app.js').read_text()+__import__('json').dumps(catalog, ensure_ascii=False))
    (OUT/'report-font.otf').rename(OUT/'review-font.otf')
    public = {name: digest(OUT/name) for name in ('index.html','app.css','app.js','review-font.otf','FONT_LICENSE.txt')}
    for folder in ('media','full','overlay'):
        public.update({f'{folder}/{name}': value for name, value in file_inventory(OUT/folder).items()})
    require(file_inventory(REPORT) == report_files, 'Original anomaly reports changed')
    require(before == protection(), 'Protected sources/configs/data changed during review package build')
    write(OUT/'source_protection.json', dict(before=before, after_identical=True,
        native_used_sha256=evidence.used, original_anomaly_report_sha256=report_files))
    manifest = dict(schema='human_anomaly_review_package_v1', target_count=len(targets), current_model_anomalies=len(current_candidates),
        full_scope_only=len(keys-current_candidates), class_atlas_count=22, rendered_reference_and_target_images=len(needed),
        catalog_sha256=digest(OUT/'catalog.json'), public_assets=public, source_protection_sha256=digest(OUT/'source_protection.json'),
        report_source_sha256={name:digest(REPORT/name) for name in ('FINAL_HANDOFF.json','all_sources.jsonl','training_sources.jsonl','visual_review.json','readonly_verification.json')},
        diagnostic_and_reference_scope='frozen annotation audit only, never model inputs or formaltest-based model selection',
        user_request='对异常图像给出人工审核界面。注：人工并不能记忆所有22类别。',
        automatic_label_application=False, original_class_assignments_changed=False, masks_changed=False, training_dataset_changed=False,
        review_store_namespace='independent_anomaly_assessment_only', no_GTinference=True,
        source_code_sha256={str(path.relative_to(PROJECT)):digest(path) for path in (Path(__file__).resolve(), PROJECT/'pallet/mask_anomaly_review.py', ASSETS/'index.html', ASSETS/'app.css', ASSETS/'app.js')})
    write(OUT/'manifest.json', manifest)
    print(dict(state='frozen_visual_class_reference_review_package_not_label_changes', targets=len(targets), current_priority=len(current_candidates),
        atlas_classes=22, unique_rendered_images=len(needed), assets=len(public)), flush=True)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--out', type=Path, default=OUT)
    build(parser.parse_args().out)
