import json

import pytest

from pallet.annotation import AnnotationSet, FrameAnnotation, Review, load_jsonl, record_review, save_jsonl
from pallet.annotation.audit_report import create_report
from pallet.data.protocol import file_digest, write_json


def test_audit_report_requires_fresh_reviewers_on_reserved_source(tmp_path):
    frame = FrameAnnotation('f', 'audit', 'raw.pcd', 16, 16,
                            split='train', source_anchor_hash='source')
    record_review(frame, Review('old-a', 'approve'), status='negative')
    record_review(frame, Review('old-b', 'approve'))
    before = tmp_path / 'before.jsonl'
    save_jsonl(AnnotationSet([frame]), before)
    after = tmp_path / 'after.jsonl'
    current = load_jsonl(before).frames['f']
    record_review(current, Review('new-d', 'approve'))
    record_review(current, Review('new-e', 'approve'))
    save_jsonl(AnnotationSet([current]), after)

    round_dir = tmp_path / 'round'
    round_dir.mkdir()
    write_json(round_dir / 'round.json', {
        'state': 'awaiting_review', 'round_id': 'r1',
        'protocol_sha256': 'protocol', 'input_labels': str(before),
        'input_labels_sha256': file_digest(before), 'audit_groups': ['audit']})
    panel = tmp_path / 'panel.json'
    write_json(panel, {'protocol_sha256': 'protocol',
                       'input_labels_sha256': file_digest(before),
                       'groups': [{'group_id': 'audit'}], 'frame_ids': ['f']})
    report = create_report(round_dir, panel, after, tmp_path / 'audit.json')
    assert report['fresh_reviewers']['f'] == ['new-d', 'new-e']
    assert report['after_labels_sha256'] == file_digest(after)

    with pytest.raises(ValueError, match='fresh independent'):
        create_report(round_dir, panel, before, tmp_path / 'bad.json')
    changed = json.loads(panel.read_text())
    changed['groups'] = [{'group_id': 'different'}]
    write_json(panel, changed)
    with pytest.raises(ValueError, match='reserved'):
        create_report(round_dir, panel, after, tmp_path / 'bad.json')
