"""Post-cleanup audit refuses incomplete or underspecified evidence."""
import ast
import importlib.util
from pathlib import Path
import sqlite3

import pytest

from test_compact_pose_v4_checkpoints import compact, environment

SCRIPT = Path(__file__).resolve().parents[1]/'scripts/verify_pose_v4_checkpoint_compaction.py'
SPEC = importlib.util.spec_from_file_location('verify_pose_v4_checkpoint_compaction', SCRIPT)
verifier = importlib.util.module_from_spec(SPEC); SPEC.loader.exec_module(verifier)


def test_incomplete_cleanup_cannot_receive_passing_verification(tmp_path, monkeypatch):
    monkeypatch.setattr(verifier, 'PROJECT', tmp_path)
    out = tmp_path/'outputs/audit'; out.mkdir(parents=True)
    (out/'result.json').write_text('{"state":"still_running"}')
    (out/'plan.json').write_text('{}'); (out/'protection_before.json').write_text('{}')
    with pytest.raises(ValueError, match='Incomplete'):
        verifier.verify(out, check_services=False)
    assert not (out/'post_cleanup_verification.json').exists()


def test_existing_verification_cannot_be_overwritten(tmp_path, monkeypatch):
    monkeypatch.setattr(verifier, 'PROJECT', tmp_path)
    out = tmp_path/'outputs/audit'; out.mkdir(parents=True)
    receipt = out/'post_cleanup_verification.json'; receipt.write_text('original audit')
    with pytest.raises(ValueError, match='Preserve'):
        verifier.verify(out, check_services=False)
    assert receipt.read_text() == 'original audit'


def test_four_model_fixture_cannot_be_reported_as_all_sixteen(environment, monkeypatch):
    project, _ = environment
    monkeypatch.setattr(verifier, 'PROJECT', project)
    out = project/'outputs/audit'; compact.plan(out); compact.apply(out, compact.digest(out/'plan.json'))
    with pytest.raises(ValueError, match='eight families'):
        verifier.verify(out, check_services=False)
    assert not (out/'post_cleanup_verification.json').exists()


def test_database_audit_preserves_utf8_payload_bytes_and_never_writes(tmp_path):
    path = tmp_path/'reviews.sqlite3'
    with sqlite3.connect(path) as db:
        db.execute('CREATE TABLE events(id INTEGER,payload TEXT)')
        db.execute('INSERT INTO events VALUES(1,?)', ('真实人工UTF-8原文',))
    before = path.read_bytes()
    one, two = verifier.fingerprint(path), verifier.fingerprint(path)
    assert one == two and path.read_bytes() == before


def test_verifier_has_no_pruner_import_or_deletion_calls():
    tree = ast.parse(SCRIPT.read_text())
    for node in ast.walk(tree):
        if isinstance(node, ast.ImportFrom):
            assert node.module != 'compact_pose_v4_checkpoints'
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
            assert node.func.attr not in ('unlink', 'rmtree', 'rmdir', 'write_text', 'write_bytes')
