import json

import pytest

from pallet.annotation.reblind_policy_examples import prepare
from pallet.data.protocol import write_json


def test_illustrated_audit_frames_are_routed_with_original_identity(tmp_path):
    review = tmp_path / 'audit'
    tasks = review / 'tasks'
    tasks.mkdir(parents=True)
    rows = [{'frame_id': fid, 'index': index,
             'views_sha256': {'intensity.png': digest}}
            for index, (fid, digest) in enumerate((('f0', 'shown'), ('f1', 'unshown')))]
    write_json(tasks / 'train_000.json', {'protocol_sha256': 'protocol', 'frames': rows})
    write_json(review / 'cache_index.json', {'f0': 'cache0', 'f1': 'cache1'})
    manifest = tmp_path / 'policy.json'
    write_json(manifest, {'examples': [{'source_sha256': 'shown'}]})
    output = tmp_path / 'reblind'
    result = prepare(tasks, manifest, output)
    task = json.loads((output / 'tasks' / 'train_000.json').read_text())
    assert result['frames'] == 1
    assert task['frames'] == [rows[0]]
    assert task['protocol_sha256'] == 'protocol'
    assert json.loads((output / 'cache_index.json').read_text()) == {'f0': 'cache0'}

    write_json(manifest, {'examples': [{'source_sha256': 'missing'}]})
    with pytest.raises(ValueError, match='uniquely locate'):
        prepare(tasks, manifest, output)
