import json
from types import SimpleNamespace

import numpy as np

from pallet import review_batches


def test_native_review_batches_can_reuse_sealed_cache(tmp_path,monkeypatch):
    protocol=tmp_path/'protocol'
    protocol.mkdir()
    (protocol/'protocol.json').write_text('{}')
    selection=tmp_path/'selection.json'
    selection.write_text(json.dumps({'train':['frame'],'val':[],'test':[]}))
    annotations=tmp_path/'labels.jsonl'
    annotations.write_text('labels')
    sealed=tmp_path/'sealed.json'
    sealed.write_text(json.dumps({'frame':{'path':str(tmp_path/'sealed.npz'),
                                            'sha256':'cache-hash'}}))
    # The real FrameRecord is a frozen dataclass; make the stub compatible
    # with dataclasses.replace for this interface test.
    from dataclasses import dataclass
    @dataclass(frozen=True)
    class Row:
        frame_id:str='frame'
        source_sha256:str='raw'
        group_id:str='group'
        domain:str='domain'
        sensor_config:dict|None=None
        paths:dict|None=None
        cache_path:str|None=None
        cache_sha256:str|None=None
    row=Row(sensor_config={},paths={})
    monkeypatch.setattr(review_batches,'load_protocol',lambda _:([row],{},{}))
    monkeypatch.setattr(review_batches,'load_jsonl',lambda _:SimpleNamespace(frames={
        'frame':SimpleNamespace(width=4,height=4)}))
    monkeypatch.setattr(review_batches,'cache_frame',
                        lambda *_:(_ for _ in ()).throw(AssertionError('raw cache copy used')))
    monkeypatch.setattr(review_batches.shutil,'disk_usage',
                        lambda _:SimpleNamespace(free=100*2**30))
    def fake_load(record,*,return_metadata=False):
        assert record.cache_path==str(tmp_path/'sealed.npz')
        assert record.cache_sha256=='cache-hash'
        values=np.zeros((4,4,4),np.float32)
        values[...,1]=2
        values[...,3]=1
        return values,{}
    monkeypatch.setattr(review_batches,'load_frame',fake_load)
    result=review_batches.prepare_batches(protocol,annotations,tmp_path/'out',
        batch_size=5,selection_path=selection,sealed_cache_index=sealed)
    assert result['frames']==1 and not result['errors'], result
    assert json.loads((tmp_path/'out'/'cache_index.json').read_text())['frame']==str(tmp_path/'sealed.npz')
    assert (tmp_path/'out'/'tasks'/'train_000.json').exists()
