"""Portable reviewed labels with native-grid previews and float tensor provenance."""
from __future__ import annotations
import argparse
from copy import deepcopy
import json
from pathlib import Path

from PIL import Image

from pallet.annotation import AnnotationSet,export_coco,export_yolo,is_resolved,load_jsonl
from pallet.cli import _attach_cache
from pallet.data.loader import load_frame
from pallet.data.protocol import file_digest,load_protocol,write_json
from pallet.review_batches import display


def export(annotations,protocol,output,subset=None):
    records,_,_=load_protocol(protocol)
    records=_attach_cache(records,'outputs/cache_v5/sealed_index.json')
    labels=load_jsonl(annotations)
    selected=set().union(*(set(ids) for ids in json.loads(Path(subset).read_text()).values())) if subset else set(labels.frames)
    output=Path(output);output.mkdir(parents=True,exist_ok=True)
    converted=AnnotationSet();sources=[];excluded=[]
    for record in records:
        if record.frame_id not in selected:continue
        label=labels.frames[record.frame_id]
        if not is_resolved(label,require_blind=label.split in {'val','test'}) or label.status=='ignore':
            excluded.append({'frame_id':record.frame_id,'status':label.status,'reason':'not a scored resolved frame'})
            continue
        key=record.source_sha256
        directory=output/'images'/label.split;directory.mkdir(parents=True,exist_ok=True)
        array=load_frame(record)
        path=directory/f'{key}.png'
        Image.fromarray(display(array[...,1],array[...,3],log=True)).save(path)
        copied=deepcopy(label);copied.image=str(path.relative_to(output))
        converted.add(copied)
        sources.append({'frame_id':record.frame_id,'image':copied.image,'native_size':[label.height,label.width],
                        'tensor_path':record.cache_path,'tensor_sha256':record.cache_sha256,
                        'source_sha256':record.source_sha256,'sensor_policy':record.sensor_config,
                        'preview_only':'display-normalized intensity PNG; float tensors are authoritative model inputs'})
    export_coco(converted,output/'annotations.coco.json')
    export_yolo(converted,output/'yolo')
    write_json(output/'sources.json',sources);write_json(output/'excluded.json',excluded)
    report={'annotation_sha256':file_digest(annotations),'protocol_sha256':file_digest(Path(protocol)/'protocol.json'),
            'resolved_scored_frames':len(sources),'excluded':len(excluded),
            'partial_ignore_note':'COCO crowd regions retained; frames with ignore_regions excluded from YOLO plain boxes'}
    write_json(output/'manifest.json',report);return report


if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--annotations',required=True);p.add_argument('--protocol',default='outputs/protocol_v5')
    p.add_argument('--output',required=True);p.add_argument('--subset');a=p.parse_args()
    print(json.dumps(export(a.annotations,a.protocol,a.output,a.subset)))
