"""Read-only post-analysis of completed research attempts; writes this directory only."""
from collections import Counter, defaultdict
import json
from pathlib import Path

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

from pallet.cluster_targets import digest, load_dataset
from pallet.mask_template_transfer import PROJECT, ImageEvidence, overlay, patch_matrix, transform, write_json
from pallet.mask_template_refined import read_jsonl


def main():
    out = Path(__file__).resolve().parent
    manifest = json.loads((out/'manifest.json').read_text())
    attempts = read_jsonl(out/'registration_attempts.jsonl')
    templates = json.loads((out/'template_inventory.json').read_text())['templates']
    formal = Path(json.loads((PROJECT/'configs/active_formal_dataset.json').read_text())['dataset'])
    _, sources = load_dataset(formal)
    rows = {r['target_key']: r for r in read_jsonl(PROJECT/'outputs/pallet_appearance_center_reclassification_v1/targets.jsonl')}
    for row in rows.values():
        row['size'] = sources[row['frame_id']]['size']
    evidence = ImageEvidence(formal, rows, sources)
    summary = {}
    figures = out/'failure_cases'; figures.mkdir(exist_ok=True)
    cases = []
    for cls in (1, 2, 9, 10, 15):
        pairs = [r for r in attempts if r['class_id'] == cls]
        photometric = [r for r in pairs if r['metrics']['configurations']]
        configs = [c for r in photometric for c in r['metrics']['configurations']]
        summary[cls] = dict(attempted_pairs=len(pairs), photometric_pass_pairs=len(photometric),
            photometric_pass_distinct_targets=len({r['target_key'] for r in photometric}),
            original_transfer_and_beam_pass_configs=sum(c['metrics'].get('original_transfer_and_beam_gates_passed', False) for c in configs),
            local_support_pass_configs=sum(c['metrics']['rejection'] is None for c in configs),
            accepted_pairs=sum(r['metrics']['rejection'] is None for r in pairs),
            configurations={f'{w}:{l}':dict(Counter(str(c['metrics']['rejection']) for c in configs
                if (c['window'], c['max_level']) == (w, l))) for w, l in [(w,l) for w in (15,25,31,19) for l in range(4)]})
        # Highest image-evidence rejected pairs, not lowest-FB cherry-picks.
        failed = sorted((r for r in photometric if r['metrics']['rejection'] is not None),
            key=lambda r: (-r['metrics']['boundary_ncc'], -r['metrics']['ecc'], r['target_key'], r['template_key']))
        seen = set()
        for record in failed:
            if record['target_key'] in seen:
                continue
            seen.add(record['target_key'])
            t = templates[record['template_key']]; target = rows[record['target_key']]
            m = record['metrics']; matrix = np.asarray(m['affine_patch_transform'])
            ref = transform(transform(transform(t['polygon'], patch_matrix(t['row'])), matrix),
                cv2.invertAffineTransform(patch_matrix(target)))
            # Show fixed window25 level0 regardless of its FB/rejection.
            example = next(c for c in m['configurations'] if c['window'] == 25 and c['max_level'] == 0)
            baseline = next(c for c in m['configurations'] if c['baseline'])
            panel = Image.new('RGB', (1480, 610), '#121923'); draw = ImageDraw.Draw(panel)
            for pos, image, row, polygon, color in [((0,30), evidence.image(t['row']['frame_id']), t['row'], t['polygon'], '#55ceff'),
                    ((740,30), evidence.image(target['frame_id']), target, ref, '#cccccc'),
                    ((0,335), evidence.image(target['frame_id']), target, example['polygon'], '#ffc247'),
                    ((740,335), evidence.image(target['frame_id']), target, baseline['polygon'], '#ff7777')]:
                panel.paste(overlay(image,row,polygon,color), pos)
            draw.text((10,8), f"Class {cls} REJECTED PAIR | source human / target affine reference (NOT acceptance)", fill='white')
            draw.text((10,310), f"target LK25 level0 FB={max(example['metrics']['forward_backward_error_patch_pixels']):.3f} / LK19 level3 FB={max(baseline['metrics']['forward_backward_error_patch_pixels']):.3f}", fill='white')
            draw.text((10,590), f"target {record['target_key']} source {record['template_key']} ECC {m['ecc']:.4f} boundaryNCC {m['boundary_ncc']:.4f}", fill='white')
            name = f"class{cls}_{record['target_key']}.png"; panel.save(figures/name)
            cases.append(dict(class_id=cls, target_key=record['target_key'], template_key=record['template_key'],
                figure='failure_cases/'+name, metrics=m,
                displayed_configuration_selection='fixed window25 level0; never acceptance based on lowest FB'))
            if len(seen) == 2:
                break
    write_json(out/'configuration_analysis.json', dict(classes=summary, source_attempts_sha256=digest(out/'registration_attempts.jsonl'),
        script_sha256=digest(__file__), algorithm_code_sha256=manifest['code_sha256']))
    write_json(out/'failure_visual_cases.json', cases)
    print(json.dumps({cls:{k:v for k,v in values.items() if k != 'configurations'}
        for cls,values in summary.items()}, indent=2))


if __name__ == '__main__':
    main()
