"""Freeze independently reviewed pilot references with complete membership checks."""
from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path

from pallet.annotation import AnnotationSet, is_resolved, load_jsonl, save_jsonl
from pallet.data.protocol import file_digest, load_protocol, write_json


def select_reviewed_batch(directory, annotations, protocol, split, output, *, limit,
                          offset=0):
    """Bind a range of fully reviewed frames in a prepared blind-review batch."""
    if split not in {'val','test'} or limit < 1 or offset < 0:
        raise ValueError('reference batch selection requires validation/test, a positive limit, and nonnegative offset')
    directory=Path(directory)
    index_path=directory/f'{split}_index.json'
    indexed=json.loads(index_path.read_text())
    if not isinstance(indexed,list):
        raise ValueError('review batch index must be a frame list')
    selected=[row for row in indexed if row.get('split')==split][offset:offset+limit]
    ids=[row.get('frame_id') for row in selected]
    if len(selected)!=limit or any(not isinstance(fid,str) for fid in ids) or len(ids)!=len(set(ids)):
        raise ValueError('review batch does not contain the requested unique frame count')
    records,assignments,_=load_protocol(protocol)
    by_id={row.frame_id:row for row in records}
    labels=load_jsonl(annotations)
    selected_by_id={row['frame_id']:row for row in selected}
    task_sources={}
    covered={}
    protocol_sha=file_digest(Path(protocol)/'protocol.json')
    for task_path in sorted((directory/'tasks').glob(f'{split}_*.json')):
        task=json.loads(task_path.read_text())
        if task.get('protocol_sha256')!=protocol_sha:
            raise ValueError(f'review task protocol changed: {task_path}')
        for task_row in task.get('frames',[]):
            fid=task_row.get('frame_id')
            if fid not in selected_by_id:
                continue
            indexed_row=selected_by_id[fid]
            record=by_id.get(fid)
            if (record is None or assignments.get(record.group_id)!=split
                    or task_row.get('split')!=split or task_row.get('group_id')!=record.group_id
                    or indexed_row.get('group_id')!=record.group_id
                    or task_row.get('source_anchor_hash')!=record.source_sha256
                    or indexed_row.get('source_anchor_hash')!=record.source_sha256):
                raise ValueError(f'review batch source identity changed: {fid}')
            if fid in covered:
                raise ValueError(f'review frame appears in more than one task: {fid}')
            frame=labels.frames.get(fid)
            if (frame is None or frame.split!=split or frame.group_id!=record.group_id
                    or frame.source_anchor_hash!=record.source_sha256
                    or not is_resolved(frame,require_blind=True)):
                raise ValueError(f'review frame is not independently resolved: {fid}')
            covered[fid]=task_path
            task_sources[str(task_path)]=file_digest(task_path)
    if set(covered)!=set(ids):
        raise ValueError('review tasks do not cover the selected frame list exactly')
    selection={'train':[],'val':[],'test':[]}
    selection[split]=ids
    output=Path(output)
    manifest={'protocol_sha256':protocol_sha,
              'source_index_sha256':file_digest(index_path),
              'source_task_sha256':task_sources,
              'review_label_path':str(Path(annotations).resolve()),
              'review_label_sha256':file_digest(annotations),
              'frames':len(ids),
              'frame_ids_sha256':hashlib.sha256(
                  json.dumps(ids,separators=(',',':'),ensure_ascii=False).encode()).hexdigest(),
              'review_role':f'independent blind {split} reference'}
    if offset:
        manifest['review_offset']=offset
    manifest_path=output.with_suffix('.manifest.json')
    if output.exists() or manifest_path.exists():
        if (not output.exists() or not manifest_path.exists()
                or json.loads(output.read_text())!=selection
                or json.loads(manifest_path.read_text())!=manifest):
            raise ValueError('existing reviewed selection differs from its bound inputs')
    else:
        write_json(output,selection)
        write_json(manifest_path,manifest)
    return manifest


def freeze(annotations, protocol, split, output, *, selection=None):
    labels=load_jsonl(annotations)
    selection_path=Path(selection) if selection else Path(protocol)/'pilot.json'
    members=json.loads(selection_path.read_text())[split]
    frames=[]
    for fid in members:
        frame=labels.frames[fid]
        if frame.split!=split or not is_resolved(frame,require_blind=True):
            raise ValueError(f'pilot reference not independently resolved: {fid}')
        frames.append(frame)
    output=Path(output)
    if output.exists():
        manifest_path=output.with_suffix('.manifest.json')
        if not manifest_path.exists():
            raise ValueError('frozen reference has no identity manifest')
        manifest=json.loads(manifest_path.read_text())
        if (manifest.get('selection_sha256',manifest.get('pilot_sha256'))!=file_digest(selection_path)
                or manifest.get('protocol_sha256')!=file_digest(Path(protocol)/'protocol.json')
                or manifest.get('label_sha256')!=file_digest(output)):
            raise ValueError('frozen reference identity differs from current selection or protocol')
        existing=load_jsonl(output)
        from dataclasses import asdict
        if {k:asdict(v) for k,v in existing.frames.items()}!={f.frame_id:asdict(f) for f in frames}:
            raise ValueError('frozen reference cannot be replaced by a new review version')
        return str(output)
    save_jsonl(AnnotationSet(frames),output)
    counts={s:sum(f.status==s for f in frames) for s in ('pos','negative','ignore')}
    write_json(output.with_suffix('.manifest.json'),{
        'split':split,'frames':len(frames),'counts':counts,
        'label_sha256':file_digest(output),
        'protocol_sha256':file_digest(Path(protocol)/'protocol.json'),
        'selection_sha256':file_digest(selection_path),
        'selection_path':str(selection_path.resolve()),
        'reference':'independent blinded machine reference, including explicit ignore coverage'})
    return str(output)


if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('--annotations',required=True)
    parser.add_argument('--protocol',default='outputs/protocol_v5')
    parser.add_argument('--selection',help='Pre-registered frame panel; defaults to protocol pilot.json')
    parser.add_argument('--review-batch',help='Generate a frozen selection from a reviewed batch index')
    parser.add_argument('--review-limit',type=int)
    parser.add_argument('--review-offset',type=int,default=0)
    parser.add_argument('--split',choices=('val','test'),required=True)
    parser.add_argument('--output',required=True)
    args=parser.parse_args()
    selection=args.selection
    if args.review_batch:
        if args.review_limit is None:
            parser.error('--review-limit is required with --review-batch')
        selection=selection or str(Path(args.review_batch)/f'reviewed_{args.review_limit}_selection.json')
        select_reviewed_batch(args.review_batch,args.annotations,args.protocol,args.split,
                              selection,limit=args.review_limit,offset=args.review_offset)
    elif args.review_limit is not None:
        parser.error('--review-limit requires --review-batch')
    elif args.review_offset:
        parser.error('--review-offset requires --review-batch')
    print(freeze(args.annotations,args.protocol,args.split,args.output,selection=selection))
