"""Original source-safety contract plus complete parallel-content coverage."""
import importlib.util
import os
from pathlib import Path

from pallet.pallet_description_parallel_guard import ParallelContentSourceGuard,CHUNK_SIZE
from pallet.cluster_targets import digest

spec=importlib.util.spec_from_file_location('_parallel_guard_contract',Path(__file__).with_name('test_mask_taxonomy_source_guard.py'))
contract=importlib.util.module_from_spec(spec);spec.loader.exec_module(contract);contract.SourceGuard=ParallelContentSourceGuard
fixture=contract.fixture
for name in dir(contract):
    if name.startswith('test_'):globals()[name]=getattr(contract,name)


def test_unchanged_sources_read_all_bytes_but_reuse_complete_sha_validation(fixture):
    guard,db,path,members=fixture;assert guard.current();before=guard.content_hash_passes;size=path.stat().st_size;bytes_before=guard.content_bytes_read
    for _ in range(5):assert guard.current()
    assert guard.content_hash_passes==before+5 and guard.content_bytes_read==bytes_before+5*size
    assert guard.stats()['full_checks']==1 and not guard.stats()['content_sampling']


def test_same_size_write_is_detected_even_with_identical_stat_stamps(fixture,monkeypatch):
    guard,db,path,members=fixture;assert guard.current();original=path.read_bytes();stamp=guard.stamp(path);real=guard.stamp
    monkeypatch.setattr(guard,'stamp',lambda p:stamp if Path(p)==path else real(p))
    path.write_bytes(original.replace(b'saved',b'other'));assert not guard.current()
    path.write_bytes(original);assert guard.current()


def test_atomic_replace_is_detected_with_same_size_and_mtime(fixture):
    guard,db,path,members=fixture;assert guard.current();before=path.stat()
    other=path.with_name('replacement.jsonl');other.write_bytes(path.read_bytes().replace(b'saved',b'other'))
    os.utime(other,ns=(before.st_atime_ns,before.st_mtime_ns));os.replace(other,path)
    assert not guard.current()


def test_far_last_chunk_modification_is_detected_not_just_header(tmp_path,monkeypatch):
    path=tmp_path/'large';path.write_bytes(b'a'*(2*CHUNK_SIZE+17));h=digest(path)
    guard=ParallelContentSourceGuard(project=tmp_path,databases={},files={'large':h},inventories={},discover_databases=lambda:set(),discover_inventories=lambda:set())
    try:
        assert guard.current();stamp=guard.stamp(path);monkeypatch.setattr(guard,'stamp',lambda p:stamp)
        with path.open('r+b') as stream:stream.seek(2*CHUNK_SIZE+16);stream.write(b'b')
        assert not guard.current()
    finally:guard.close()


def test_short_read_fails_closed_and_closes_descriptors(fixture,monkeypatch):
    import pallet.pallet_description_parallel_guard as module
    guard,db,path,members=fixture;real=module.os.pread
    monkeypatch.setattr(module.os,'pread',lambda fd,size,offset:real(fd,max(0,size-1),offset))
    assert not guard.current() and not guard.valid


def test_empty_files_and_changed_length_are_covered(tmp_path):
    path=tmp_path/'empty';path.write_bytes(b'');guard=ParallelContentSourceGuard(project=tmp_path,databases={},files={'empty':digest(path)},inventories={},discover_databases=lambda:set(),discover_inventories=lambda:set())
    try:
        assert guard.current();path.write_bytes(b'changed');assert not guard.current()
    finally:guard.close()


def test_concurrent_change_during_probe_does_not_get_trusted(fixture,monkeypatch):
    guard,db,path,members=fixture;real=guard._fingerprints
    def change():
        result=real();path.write_text(path.read_text()+' ');return result
    monkeypatch.setattr(guard,'_fingerprints',change);assert not guard.current()


def test_close_rejects_future_operations(fixture):
    guard,db,path,members=fixture;assert guard.current();guard.close();assert not guard.current()
