#!/usr/bin/env python3
"""
Tamper KATs - Prove frozen hash guards bite.

Tests that attempting to mutate frozen values causes import-time failures
with exact drift messages.

Three tests:
1. CODE_VOCAB mutation
2. TOKEN_CLASS mutation
3. VOCAB_META mutation
"""
import sys
import subprocess
from pathlib import Path

def test_vocab_tamper():
    """Test: Mutating CODE_VOCAB causes import failure."""
    print("\n1. CODE_VOCAB tamper test")

    # Create tampered module
    tamper_code = '''
import sys
sys.path.insert(0, "/home/voidstr3m33/helix-cdc")

# Tamper with CODE_VOCAB before import
from helix_cdc import glyphscope_code
glyphscope_code.CODE_VOCAB[0] = "TAMPERED"

# Trigger validation
glyphscope_code._validate_vocab_frozen()
'''

    result = subprocess.run(
        [sys.executable, "-c", tamper_code],
        capture_output=True,
        text=True
    )

    if result.returncode != 0 and "CODE_VOCAB order drift detected" in result.stderr:
        print("✅ PASS: CODE_VOCAB guard bit (import failed with drift message)")
        return True
    else:
        print(f"❌ FAIL: CODE_VOCAB guard didn't bite")
        print(f"   Exit code: {result.returncode}")
        print(f"   Stderr: {result.stderr[:200]}")
        return False

def test_token_class_tamper():
    """Test: Mutating TOKEN_CLASS causes import failure."""
    print("\n2. TOKEN_CLASS tamper test")

    tamper_code = '''
import sys
sys.path.insert(0, "/home/voidstr3m33/helix-cdc")

# Tamper with TOKEN_CLASS before validation
from helix_cdc import glyphscope_code
glyphscope_code.TOKEN_CLASS["def"] = "TAMPERED"

# Trigger validation
glyphscope_code._validate_token_class_frozen()
'''

    result = subprocess.run(
        [sys.executable, "-c", tamper_code],
        capture_output=True,
        text=True
    )

    if result.returncode != 0 and "TOKEN_CLASS drift detected" in result.stderr:
        print("✅ PASS: TOKEN_CLASS guard bit (import failed with drift message)")
        return True
    else:
        print(f"❌ FAIL: TOKEN_CLASS guard didn't bite")
        print(f"   Exit code: {result.returncode}")
        print(f"   Stderr: {result.stderr[:200]}")
        return False

def test_vocab_meta_tamper():
    """Test: Mutating VOCAB_META is detected on re-hash."""
    print("\n3. VOCAB_META tamper test")

    tamper_code = '''
import sys
sys.path.insert(0, "/home/voidstr3m33/helix-cdc")

# Tamper with VOCAB_META
from helix_cdc import glyphscope_code
glyphscope_code.VOCAB_META["size"] += 1

# Re-compute hash
actual = glyphscope_code._compute_vocab_meta_hash()
expected = glyphscope_code.VOCAB_META_FROZEN_SHA256

if actual == expected:
    print("ERROR: Tamper not detected!")
    sys.exit(1)
else:
    print(f"Tamper detected: hash changed")
    sys.exit(0)
'''

    result = subprocess.run(
        [sys.executable, "-c", tamper_code],
        capture_output=True,
        text=True
    )

    if result.returncode == 0 and "Tamper detected" in result.stdout:
        print("✅ PASS: VOCAB_META tamper detected (hash changed)")
        return True
    else:
        print(f"❌ FAIL: VOCAB_META tamper not detected")
        print(f"   Exit code: {result.returncode}")
        print(f"   Stdout: {result.stdout[:200]}")
        return False

def main():
    print("=== Tamper KATs (Frozen Hash Guards) ===")
    print("\nThese tests prove that mutating frozen values triggers")
    print("import-time failures with exact drift messages.")

    results = []
    results.append(test_vocab_tamper())
    results.append(test_token_class_tamper())
    results.append(test_vocab_meta_tamper())

    if all(results):
        print("\n✅ ALL TAMPER TESTS PASSED (guards bite)")
        return 0
    else:
        print(f"\n❌ SOME TAMPER TESTS FAILED ({sum(results)}/3 passed)")
        return 1

if __name__ == "__main__":
    sys.exit(main())
