import json
from types import SimpleNamespace

import pytest

from pallet.annotation import (AnnotationSet, FrameAnnotation, Review, record_review,
                              save_jsonl)
from pallet.data.protocol import file_digest, write_json
from pallet.freeze_references import freeze, select_reviewed_batch


def test_pre_registered_panel_freeze_requires_blind_resolution_and_is_immutable(tmp_path):
    protocol = tmp_path / 'protocol'
    protocol.mkdir()
    (protocol / 'protocol.json').write_text('{}')
    write_json(protocol / 'pilot.json', {'val': []})
    selection = tmp_path / 'paired.json'
    write_json(selection, {'val': ['f']})
    frame = FrameAnnotation('f', 'g', 'raw.pcd', 16, 16,
                            split='val', source_anchor_hash='source')
    labels = tmp_path / 'labels.jsonl'
    save_jsonl(AnnotationSet([frame]), labels)
    output = tmp_path / 'reference.jsonl'
    with pytest.raises(ValueError, match='not independently resolved'):
        freeze(labels, protocol, 'val', output, selection=selection)

    record_review(frame, Review('a', 'approve', blind=True), status='negative')
    record_review(frame, Review('b', 'approve', blind=True))
    save_jsonl(AnnotationSet([frame]), labels)
    assert freeze(labels, protocol, 'val', output, selection=selection) == str(output)
    manifest = json.loads(output.with_suffix('.manifest.json').read_text())
    assert manifest['selection_sha256'] == file_digest(selection)
    assert manifest['counts'] == {'pos': 0, 'negative': 1, 'ignore': 0}
    assert freeze(labels, protocol, 'val', output, selection=selection) == str(output)

    changed = FrameAnnotation('f', 'g', 'raw.pcd', 16, 16,
                              split='val', source_anchor_hash='source')
    record_review(changed, Review('c', 'approve', blind=True), status='ignore')
    record_review(changed, Review('d', 'approve', blind=True))
    save_jsonl(AnnotationSet([changed]), labels)
    with pytest.raises(ValueError, match='cannot be replaced'):
        freeze(labels, protocol, 'val', output, selection=selection)

    write_json(selection, {'val': ['f'], 'note': 'changed selection identity'})
    with pytest.raises(ValueError, match='identity differs'):
        freeze(labels, protocol, 'val', output, selection=selection)


def test_reviewed_batch_selection_binds_tasks_and_requires_blind_resolution(tmp_path,monkeypatch):
    protocol=tmp_path/'protocol'
    protocol.mkdir()
    (protocol/'protocol.json').write_text('{}')
    task_dir=tmp_path/'batch/tasks'
    task_dir.mkdir(parents=True)
    batch=task_dir.parent
    record=SimpleNamespace(frame_id='f',group_id='g',source_sha256='source')
    monkeypatch.setattr('pallet.freeze_references.load_protocol',
                        lambda _: ([record],{'g':'val'},{}))
    protocol_sha=file_digest(protocol/'protocol.json')
    index_row={'frame_id':'f','group_id':'g','split':'val',
               'source_anchor_hash':'source','width':16,'height':16}
    write_json(batch/'val_index.json',[index_row])
    task_path=task_dir/'val_000.json'
    write_json(task_path,{'task_id':'val_000','protocol_sha256':protocol_sha,
                          'frames':[dict(index_row,index=0)]})
    frame=FrameAnnotation('f','g','raw.pcd',16,16,split='val',
                          source_anchor_hash='source')
    labels=tmp_path/'labels.jsonl'
    save_jsonl(AnnotationSet([frame]),labels)
    selection=tmp_path/'reviewed_selection.json'
    with pytest.raises(ValueError,match='not independently resolved'):
        select_reviewed_batch(batch,labels,protocol,'val',selection,limit=1)

    record_review(frame,Review('a','approve',blind=True),status='negative')
    record_review(frame,Review('b','approve',blind=True))
    save_jsonl(AnnotationSet([frame]),labels)
    binding=select_reviewed_batch(batch,labels,protocol,'val',selection,limit=1)
    assert json.loads(selection.read_text())=={'train':[],'val':['f'],'test':[]}
    assert binding['source_task_sha256'][str(task_path)]==file_digest(task_path)
    assert binding['review_label_sha256']==file_digest(labels)
    reference=tmp_path/'reference.jsonl'
    freeze(labels,protocol,'val',reference,selection=selection)
    frozen=json.loads(reference.with_suffix('.manifest.json').read_text())
    assert frozen['counts']=={'pos':0,'negative':1,'ignore':0}


def test_reviewed_batch_selection_supports_offset_without_reselecting_first_batch(tmp_path,monkeypatch):
    protocol=tmp_path/'protocol'
    protocol.mkdir()
    (protocol/'protocol.json').write_text('{}')
    batch=tmp_path/'batch'
    (batch/'tasks').mkdir(parents=True)
    records=[SimpleNamespace(frame_id=f'f{i}',group_id=f'g{i}',source_sha256=f'source{i}')
             for i in range(2)]
    monkeypatch.setattr('pallet.freeze_references.load_protocol',
                        lambda _: (records,{f'g{i}':'val' for i in range(2)},{}))
    protocol_sha=file_digest(protocol/'protocol.json')
    rows=[]
    frames=[]
    for index,record in enumerate(records):
        row={'frame_id':record.frame_id,'group_id':record.group_id,'split':'val',
             'source_anchor_hash':record.source_sha256,'width':16,'height':16}
        rows.append(row)
        task={'task_id':f'val_{index:03d}','protocol_sha256':protocol_sha,
              'frames':[dict(row,index=0)]}
        write_json(batch/'tasks'/f'val_{index:03d}.json',task)
        frame=FrameAnnotation(record.frame_id,record.group_id,'raw.pcd',16,16,
                              split='val',source_anchor_hash=record.source_sha256)
        record_review(frame,Review(f'a{index}','approve',blind=True),status='ignore')
        record_review(frame,Review(f'b{index}','approve',blind=True))
        frames.append(frame)
    write_json(batch/'val_index.json',rows)
    labels=tmp_path/'labels.jsonl'
    save_jsonl(AnnotationSet(frames),labels)
    selection=tmp_path/'second_selection.json'

    binding=select_reviewed_batch(batch,labels,protocol,'val',selection,limit=1,offset=1)

    assert json.loads(selection.read_text())=={'train':[],'val':['f1'],'test':[]}
    assert binding['review_offset']==1
    assert binding['source_task_sha256']=={
        str(batch/'tasks/val_001.json'):file_digest(batch/'tasks/val_001.json')
    }
