from dataclasses import asdict
import json

import numpy as np
from PIL import Image

from pallet.annotation import AnnotationSet,Box,FrameAnnotation,Review,record_review,save_jsonl
from pallet.cli import build_parser
from pallet.data.manifest import FrameRecord
from pallet.data.protocol import file_digest,write_json


def test_rf_cli_trains_and_evaluates_a_frozen_protocol(tmp_path):
    import torch
    torch.set_num_threads(1)
    root=tmp_path/'raw';root.mkdir()
    protocol=tmp_path/'protocol';protocol.mkdir()
    rows=[];frames=[];assignments={}
    for idx,split in enumerate(('train','val')):
        intensity=root/f'i{idx}.png';depth=root/f'd{idx}.png'
        Image.fromarray(np.full((32,48),100+idx,np.uint16)).save(intensity)
        Image.fromarray(np.full((32,48),2000+idx,np.uint16)).save(depth)
        source=file_digest(intensity)
        row=FrameRecord(f'f{idx}',f'g{idx}','original',{'intensity':intensity,'depth':depth},
                        {'grid':[32,48],'depth_available':True,'depth_source':'depth',
                         'scale_to_mm':1,'rasters_aligned':True,'domain_id':'synthetic'},source)
        obj=row.to_dict();obj['source_stat']={str(p):{'size':p.stat().st_size,'mtime_ns':p.stat().st_mtime_ns}
                                             for p in row.paths.values()}
        rows.append(obj);assignments[row.group_id]=split
        frame=FrameAnnotation(row.frame_id,row.group_id,str(intensity),48,32,split=split,source_anchor_hash=source)
        record_review(frame,Review('synthetic-a','approve'),status='pos',boxes=[Box(12,8,20,14)])
        record_review(frame,Review('synthetic-b','approve'))
        frames.append(frame)
    (protocol/'manifest.jsonl').write_text(''.join(json.dumps(r)+'\n' for r in rows))
    write_json(protocol/'splits.json',{'assignments':assignments})
    write_json(protocol/'protocol.json',{'root':str(root.resolve()),'split_seed':42,
                'files':{name:file_digest(protocol/name) for name in ['manifest.jsonl','splits.json']}})
    labels=tmp_path/'labels.jsonl';save_jsonl(AnnotationSet(frames),labels)
    parser=build_parser();output=tmp_path/'run'
    common=['--root',str(root),'--protocol',str(protocol),'--annotations',str(labels),'--cache-index','']
    train=parser.parse_args(['train',*common,'--family','rfdetr-small','--scratch','--epochs','1',
                             '--size','64','--device','cpu','--batch-size','1','--effective-batch','1','--output',str(output)])
    train.func(train)
    assert (output/'completed.json').exists()
    result=tmp_path/'evaluation.json'
    evaluate=parser.parse_args(['evaluate',*common,'--checkpoint',str(output/'best.pt'),
                                '--split','val','--device','cpu','--output',str(result)])
    evaluate.func(evaluate)
    report=json.loads(result.read_text())
    assert report['images']==1 and report['reference_coverage']['scored_frames']==1
