#!/usr/bin/env python3
"""Compare current visible manual labels with immutable original detections, locally."""
import collections
import hashlib
import json
import math
import statistics
import sys
from pathlib import Path

source = Path(sys.argv[1])
data = source.read_bytes()
doc = json.loads(data)
rows = []
counts = collections.Counter()
for frame in doc['frames']:
    panel = frame['panel']
    for name, edit in frame['edits'].items():
        counts[edit['state']] += 1
        if edit['state'] not in ('corrected', 'confirmed') or not edit.get('point'):
            continue
        row = dict(frame=frame['id'], joint=name, errors={})
        for kind in ('3D', '2D'):
            pose = frame.get('raw' + kind) or {}
            joint = next((j for j in pose.get('joints', []) if j['name'] == name), None)
            if pose.get('status') != 'needsReview' or not joint:
                continue
            p = joint['point']
            if (joint.get('confidence2D', 1) < .2 or not (panel['x'] <= p['x'] < panel['x'] + panel['width'] and panel['y'] <= p['y'] < panel['y'] + panel['height'])):
                continue
            q = edit['point']
            pixels = math.hypot(p['x'] - q['x'], p['y'] - q['y'])
            row['errors'][kind] = dict(pixels=pixels, panelDiagonalPercent=100 * pixels / math.hypot(panel['width'], panel['height']))
        rows.append(row)
paired = [r for r in rows if len(r['errors']) == 2]
report = dict(reviewSHA256=hashlib.sha256(data).hexdigest(), revision=doc['revision'], decisions=dict(counts), reviewedFrames=sum(bool(f['edits']) for f in doc['frames']), visibleLabels=len(rows), matchedBoth=len(paired),
              pairedMedianPixels={k: statistics.median(r['errors'][k]['pixels'] for r in paired) if paired else None for k in ('3D', '2D')}, rows=rows)
print(json.dumps(report, indent=2))
