from concurrent.futures import ThreadPoolExecutor
import json
import os
from pathlib import Path
import sqlite3

import pytest

from pallet.cluster_targets import digest
from pallet.mask_quality_recovery import fingerprint
from pallet.mask_taxonomy_source_guard import SourceGuard


@pytest.fixture
def fixture(tmp_path):
    db=sqlite3.connect(tmp_path/'source.sqlite3');db.execute('PRAGMA journal_mode=WAL');db.execute('PRAGMA wal_autocheckpoint=0')
    db.execute('CREATE TABLE events(id INTEGER PRIMARY KEY,payload TEXT)');db.execute("INSERT INTO events VALUES (1,'original')");db.commit()
    path=tmp_path/'inventory.jsonl';path.write_text('{"target_key":"saved"}\n')
    members={'db':{'source.sqlite3'},'inv':{'inventory.jsonl'}}
    guard=SourceGuard(project=tmp_path,databases={'source.sqlite3':fingerprint(tmp_path/'source.sqlite3')},
        files={'inventory.jsonl':digest(path)},inventories={'inventory.jsonl':digest(path)},
        discover_databases=lambda:set(members['db']),discover_inventories=lambda:set(members['inv']))
    yield guard,db,path,members
    guard.close();db.close()


def test_unchanged_sources_use_one_full_verification(fixture):
    guard,db,path,members=fixture
    for _ in range(20):assert guard.current()
    assert guard.stats()['full_checks']==1
    with pytest.raises(sqlite3.OperationalError):guard.connections['source.sqlite3'][1].execute("INSERT INTO events VALUES(2,'forbidden')")


def test_inventory_is_hashed_not_json_decoded(fixture,monkeypatch):
    guard,db,path,members=fixture
    monkeypatch.setattr(json,'loads',lambda *a,**k:(_ for _ in ()).throw(AssertionError('unnecessary JSON parsing')))
    assert guard.current()


def test_parallel_requests_share_one_full_check(fixture):
    guard,db,path,members=fixture
    with ThreadPoolExecutor(max_workers=8) as pool:assert all(pool.map(lambda _:guard.current(),range(24)))
    assert guard.stats()['full_checks']==1


def test_WAL_commit_invalidates_without_main_file_change(fixture):
    guard,db,path,members=fixture;assert guard.current();stamp=(path.parent/'source.sqlite3').stat().st_mtime_ns
    db.execute("INSERT INTO events VALUES (2,'new human revision')");db.commit()
    assert (path.parent/'source.sqlite3').stat().st_mtime_ns==stamp
    assert not guard.current() and not guard.current() and guard.stats()['full_checks']==2


def test_data_version_detects_commit_even_if_file_stamps_appear_unchanged(fixture,monkeypatch):
    guard,db,path,members=fixture;assert guard.current();original=guard.stamp
    stamps={str(p):original(p) for p in (path,path.parent/'source.sqlite3',path.parent/'source.sqlite3-wal')}
    monkeypatch.setattr(guard,'stamp',lambda p:stamps.get(str(p),original(p)))
    db.execute("UPDATE events SET payload='changed' WHERE id=1");db.commit()
    assert not guard.current()


def test_same_size_file_edit_with_restored_mtime_is_detected(fixture):
    guard,db,path,members=fixture;assert guard.current();before=path.stat();text=path.read_text()
    path.write_text(text.replace('saved','other'));os.utime(path,ns=(before.st_atime_ns,before.st_mtime_ns))
    assert path.stat().st_size==before.st_size and not guard.current()
    path.write_text(text);assert guard.current()


@pytest.mark.parametrize('kind',['inv','db'])
def test_new_or_removed_inventory_invalidates_immediately(fixture,kind):
    guard,db,path,members=fixture;assert guard.current();members[kind].add('unexpected')
    assert not guard.current();members[kind].remove('unexpected');assert guard.current()


def test_missing_source_fails_closed_and_recovery_rechecks(fixture):
    guard,db,path,members=fixture;assert guard.current();original=path.read_bytes();path.unlink()
    assert not guard.current();path.write_bytes(original);assert guard.current()


def test_checkpoint_change_revalidates_logical_history(fixture):
    guard,db,path,members=fixture;assert guard.current();db.execute('PRAGMA wal_checkpoint(TRUNCATE)')
    assert guard.current() and guard.stats()['full_checks']>=2


def test_SQLite_WAL_permission_touch_does_not_trigger_false_full_recheck(fixture):
    guard,db,path,members=fixture;assert guard.current();wal=Path(str(path.parent/'source.sqlite3')+'-wal')
    os.chmod(wal,wal.stat().st_mode)
    assert guard.current() and guard.stats()['full_checks']==1


def test_sources_changing_during_validation_are_not_trusted(fixture,monkeypatch):
    guard,db,path,members=fixture;original=guard._full_check
    def change_after_check():
        result=original();path.write_text(path.read_text()+' ');return result
    monkeypatch.setattr(guard,'_full_check',change_after_check)
    assert not guard.current() and not guard.valid


def test_conflicting_frozen_hashes_are_rejected(tmp_path):
    with pytest.raises(ValueError,match='Conflicting'):
        SourceGuard(project=tmp_path,databases={},files={'one':'a'},inventories={'one':'b'},discover_databases=lambda:set(),discover_inventories=lambda:set())


def test_database_path_replacement_is_detected(tmp_path):
    path=tmp_path/'source.sqlite3'
    with sqlite3.connect(path) as db:db.execute('CREATE TABLE history(payload TEXT)');db.execute("INSERT INTO history VALUES ('original')")
    guard=SourceGuard(project=tmp_path,databases={'source.sqlite3':fingerprint(path)},files={},inventories={},discover_databases=lambda:{'source.sqlite3'},discover_inventories=lambda:set())
    try:
        assert guard.current()
        replacement=tmp_path/'replacement.sqlite3'
        with sqlite3.connect(replacement) as db:db.execute('CREATE TABLE history(payload TEXT)');db.execute("INSERT INTO history VALUES ('replacement')")
        os.replace(replacement,path);assert not guard.current()
    finally:guard.close()
