import hashlib
import io
import json
import tarfile

import pytest

from pallet.replay_evaluate import restore_source


def _snapshot(tmp_path, *, archive_payload=b'original'):
    manifest = {'pallet/example.py': hashlib.sha256(b'original').hexdigest()}
    identity = hashlib.sha256(json.dumps(manifest, sort_keys=True).encode()).hexdigest()
    archive = tmp_path / f'{identity}.tar.gz'
    with tarfile.open(archive, 'w:gz') as stream:
        info = tarfile.TarInfo('pallet/example.py')
        info.size = len(archive_payload)
        stream.addfile(info, io.BytesIO(archive_payload))
    (tmp_path / f'{identity}.json').write_text(json.dumps(manifest))
    return {'source_snapshot': str(archive), 'source_snapshot_id': identity}


def test_source_replay_checks_archive_and_existing_payload(tmp_path):
    run = _snapshot(tmp_path)
    directory = restore_source(run, tmp_path / 'restore')
    assert (directory / 'pallet/example.py').read_bytes() == b'original'
    assert restore_source(run, tmp_path / 'restore') == directory
    (directory / 'pallet/example.py').write_bytes(b'changed')
    with pytest.raises(ValueError, match='existing replayed source differs'):
        restore_source(run, tmp_path / 'restore')


def test_source_replay_rejects_changed_archive_and_manifest(tmp_path):
    run = _snapshot(tmp_path, archive_payload=b'tampered')
    with pytest.raises(ValueError, match='archive payload changed'):
        restore_source(run, tmp_path / 'restore')
    changed = {**run, 'source_snapshot_id': 'another-identity'}
    with pytest.raises(ValueError, match='manifest differs'):
        restore_source(changed, tmp_path / 'restore')
