import json

from pallet.annotation import AnnotationSet, Box, FrameAnnotation, Review, record_review, save_jsonl
from pallet.data.protocol import file_digest
from pallet.research_log import collect_references, collect_run, render_training_log


def test_best_checkpoint_without_completion_is_not_a_completed_run(tmp_path):
    (tmp_path / 'run.json').write_text('{}')
    (tmp_path / 'best.pt').write_bytes(b'checkpoint')
    result = collect_run(tmp_path)
    assert result['state'] == 'no_completion_marker'
    assert result['test_score_present'] is False


def test_completion_requires_configuration_and_checkpoint_hashes(tmp_path):
    run = tmp_path / 'run.json'
    best = tmp_path / 'best.pt'
    run.write_text('{}')
    best.write_bytes(b'checkpoint')
    (tmp_path / 'completed.json').write_text(json.dumps({
        'run_config_sha256': file_digest(run),
        'best_checkpoint_sha256': file_digest(best), 'completed_epochs': 1,
    }))
    assert collect_run(tmp_path)['state'] == 'complete_verified'
    best.write_bytes(b'changed checkpoint')
    assert collect_run(tmp_path)['state'] == 'completion_mismatch'


def test_frozen_reference_counts_deduplicate_overlapping_panels(tmp_path):
    directory = tmp_path / 'outputs/protocol_v5/references'
    directory.mkdir(parents=True)
    frame = FrameAnnotation('f', 'g', 'raw', 16, 16, split='val', source_anchor_hash='source')
    record_review(frame, Review('a', 'approve', blind=True), status='negative')
    record_review(frame, Review('b', 'approve', blind=True))
    for name in ('pilot_val', 'paired_val'):
        path = directory / f'{name}.jsonl'
        save_jsonl(AnnotationSet([frame]), path)
        path.with_suffix('.manifest.json').write_text(json.dumps({
            'split': 'val', 'frames': 1, 'label_sha256': file_digest(path),
        }))
    references, coverage = collect_references(tmp_path)
    assert len(references) == 2
    assert all(item['verified'] for item in references)
    assert coverage['val']['unique_frozen_frames'] == 1
    assert coverage['val']['counts'] == {'negative': 1}
    assert coverage['val']['consistent_frames'] == 1
    assert coverage['val']['scorable_consistent_frames'] == 1


def test_same_status_different_boxes_remain_reference_conflicts(tmp_path):
    directory = tmp_path / 'outputs/protocol_v5/references'
    directory.mkdir(parents=True)
    for index, name in enumerate(('pilot_test', 'paired_test')):
        frame = FrameAnnotation('f', 'g', 'raw', 16, 16, split='test', source_anchor_hash='source')
        record_review(frame, Review('a', 'approve', blind=True), status='pos',
                      boxes=[Box(index + 1, 1, 4, 4)])
        record_review(frame, Review('b', 'approve', blind=True))
        path = directory / f'{name}.jsonl'
        save_jsonl(AnnotationSet([frame]), path)
        path.with_suffix('.manifest.json').write_text(json.dumps({
            'split': 'test', 'frames': 1, 'label_sha256': file_digest(path),
        }))
    _, coverage = collect_references(tmp_path)
    assert coverage['test']['status_conflicts'] == 0
    assert coverage['test']['payload_conflicts'] == 1
    assert coverage['test']['conflicting_frame_ids'] == ['f']
    assert coverage['test']['consistent_frames'] == 0
    assert coverage['test']['scorable_consistent_frames'] == 0


def test_reference_manifest_cannot_reclassify_the_frame_split(tmp_path):
    directory = tmp_path / 'outputs/protocol_v5/references'
    directory.mkdir(parents=True)
    frame = FrameAnnotation('f', 'g', 'raw', 16, 16, split='train', source_anchor_hash='source')
    record_review(frame, Review('a', 'approve', blind=True), status='negative')
    record_review(frame, Review('b', 'approve', blind=True))
    path = directory / 'test.jsonl'
    save_jsonl(AnnotationSet([frame]), path)
    path.with_suffix('.manifest.json').write_text(json.dumps({
        'split': 'test', 'frames': 1, 'label_sha256': file_digest(path),
    }))
    references, coverage = collect_references(tmp_path)
    assert references[0]['verified'] is False
    assert coverage['test']['unique_frozen_frames'] == 0


def test_training_log_can_refresh_after_a_round_is_frozen():
    data = {'captured_at_utc': '2026-09-30T00:00:00+00:00', 'runs': [],
            'progress': {'candidate_rounds': {'006': {
                'round_state': 'complete', 'planned': 256, 'resolved': 256,
                'pending_adjudication': 0, 'review_progress': None}}},
            'reference_coverage': {}}
    rendered = render_training_log(data, 'outputs/session_logs/snapshot.json')
    assert '| 006 | complete | 256/256 |' in rendered
    assert 'outputs/session_logs/snapshot.json' in rendered
