import json

import pytest
from PIL import Image

from pallet.annotation import AnnotationSet, Box, FrameAnnotation, Review, record_review, save_jsonl
from pallet.annotation import make_policy_examples_v4
from pallet.data.protocol import file_digest, write_json


def test_policy_examples_exclude_audit_groups_and_bind_original_views(tmp_path, monkeypatch):
    image=tmp_path/'intensity.png'
    Image.new('L',(20,10),128).save(image)
    frame=FrameAnnotation('frame','train','raw.pcd',20,10,split='train',
                          source_anchor_hash='raw',status='pos',boxes=[Box(1,2,8,5)])
    record_review(frame,Review('a','approve',blind=True))
    record_review(frame,Review('b','approve',blind=True))
    labels=tmp_path/'labels.jsonl'
    save_jsonl(AnnotationSet([frame]),labels)
    task=tmp_path/'task.json'
    write_json(task,{'frames':[{'frame_id':'frame','group_id':'train',
                                'source_anchor_hash':'raw','intensity':str(image),
                                'views_sha256':{'intensity.png':file_digest(image)}}]})
    monkeypatch.setattr(make_policy_examples_v4,'EXAMPLES',(('example.png','frame',str(task)),))
    audit=tmp_path/'audit.json'
    write_json(audit,['other'])
    rendered=make_policy_examples_v4.render(labels_path=labels,audit_groups_path=audit,
                                            output_dir=tmp_path/'rendered')
    assert rendered[0]['group_id']=='train'
    manifest=json.loads((tmp_path/'rendered'/'manifest.json').read_text())
    assert manifest['labels_sha256']==file_digest(labels)
    write_json(audit,['train'])
    with pytest.raises(ValueError,match='non-audit'):
        make_policy_examples_v4.render(labels_path=labels,audit_groups_path=audit,
                                       output_dir=tmp_path/'blocked')
