"""Normalize blind review exports without changing their original evidence files."""
from __future__ import annotations

import argparse
import json
from pathlib import Path

from pallet.data.protocol import file_digest, write_json


def normalize_batch(task_path, review_path, output_path):
    task = json.loads(Path(task_path).read_text())
    review = json.loads(Path(review_path).read_text())
    if task['task_id'] != review['task_id'] or not review.get('blind'):
        raise ValueError('review is not a blind response to the requested task')
    source = review.get('frames', review.get('decisions'))
    if not isinstance(source, list) or len(source) != len(task['frames']):
        raise ValueError('review must contain one decision per task frame')
    if all('frame_id' in entry for entry in source):
        by_key = {entry['frame_id']:entry for entry in source}
        if len(by_key)!=len(source) or set(by_key)!={row['frame_id'] for row in task['frames']}:
            raise ValueError('review frame ids differ from the frozen task')
        lookup=lambda row:by_key[row['frame_id']]
    elif all('index' in entry for entry in source):
        by_key = {entry['index']:entry for entry in source}
        if len(by_key)!=len(source) or set(by_key)!={row['index'] for row in task['frames']}:
            raise ValueError('review indices differ from the frozen task')
        lookup=lambda row:by_key[row['index']]
    else:
        raise ValueError('review entries need either all frame ids or all task indices')
    normalized = []
    for row in task['frames']:
        entry = lookup(row)
        status = entry.get('status', entry.get('decision'))
        status = {'positive':'pos', 'empty':'negative'}.get(status, status)
        boxes = entry.get('boxes', entry.get('instances', []))
        xywh = [box['xywh'] if isinstance(box, dict) else box for box in boxes]
        reason = entry.get('reason') or entry.get('ignore_reason') or ''
        if status not in {'pos','negative','ignore'} or bool(xywh) != (status == 'pos'):
            raise ValueError(f'invalid status and boxes: {row["frame_id"]}')
        if status == 'ignore' and not reason.strip():
            raise ValueError(f'ignored frame needs evidence reason: {row["frame_id"]}')
        if any(not isinstance(box, (list,tuple)) or len(box)!=4 or
               box[2]<=0 or box[3]<=0 or box[0]<0 or box[1]<0 or
               box[0]+box[2]>row['width'] or box[1]+box[3]>row['height']
               for box in xywh):
            raise ValueError(f'box outside native grid: {row["frame_id"]}')
        uncertainty=entry.get('uncertainty')
        if uncertainty not in ('low','medium','high'):
            uncertainty='high' if status=='ignore' else 'medium'
        normalized.append({'index':row['index'], 'status':status, 'boxes':xywh,
                           'tags':entry.get('tags',[]), 'reason':reason,
                           'uncertainty':uncertainty})
    result = {'task_id': task['task_id'], 'reviewer': review['reviewer'],
              'blind': True, 'frames': normalized}
    output_path = Path(output_path)
    manifest_path = output_path.with_suffix('.manifest.json')
    manifest = {'task_sha256':file_digest(task_path),
                'original_review_sha256':file_digest(review_path),
                'normalized_review_sha256':None,
                'policy':'lossless status/box/reason mapping; unknown uncertainty defaults high for ignore'}
    if output_path.exists() and json.loads(output_path.read_text()) != result:
        raise ValueError('existing normalized review differs')
    write_json(output_path,result)
    manifest['normalized_review_sha256'] = file_digest(output_path)
    if manifest_path.exists() and json.loads(manifest_path.read_text()) != manifest:
        raise ValueError('existing normalization manifest differs')
    write_json(manifest_path,manifest)
    return manifest


if __name__ == '__main__':
    parser=argparse.ArgumentParser()
    parser.add_argument('--task',required=True)
    parser.add_argument('--review',required=True)
    parser.add_argument('--output',required=True)
    args=parser.parse_args()
    print(json.dumps(normalize_batch(args.task,args.review,args.output)))
