#!/usr/bin/env python3
"""
Time/OS invariance KAT.

Proves: env_fingerprint captures platform info, but output remains deterministic
across runs (same seed → same output, regardless of timestamp).
"""
import os
import sys

os.environ["VAULT_DISABLED"] = "1"

from helix_cdc.cdc_decode import CDCDecoder

def main():
    print("=== Time/OS Invariance KAT ===")

    # Test 1: env_fingerprint is present
    print("\nTest 1: env_fingerprint in receipts")
    dec = CDCDecoder(seed_path=None)
    _, tr = dec.generate_from_anchor("", max_new_tokens=64, temperature=0.2, seed=42)

    assert "env_fingerprint" in tr, "Expected env_fingerprint in receipt"
    fp = tr["env_fingerprint"]

    required_fields = ["python_version", "platform", "platform_release", "machine", "timestamp_utc"]
    for field in required_fields:
        assert field in fp, f"Expected {field} in env_fingerprint"

    print(f"✅ env_fingerprint present: {fp['platform']} {fp['platform_release']}, Python {fp['python_version']}")
    print(f"   Machine: {fp['machine']}, Timestamp: {fp['timestamp_utc']}")

    # Test 2: Determinism despite timestamp change (run twice, different timestamps)
    print("\nTest 2: Output invariant despite timestamp change")
    import time

    dec1 = CDCDecoder(seed_path=None)
    txt1, tr1 = dec1.generate_from_anchor("", max_new_tokens=64, temperature=0.2, seed=999)
    fp1 = tr1["env_fingerprint"]["timestamp_utc"]

    time.sleep(2)  # Wait for timestamp to change

    dec2 = CDCDecoder(seed_path=None)
    txt2, tr2 = dec2.generate_from_anchor("", max_new_tokens=64, temperature=0.2, seed=999)
    fp2 = tr2["env_fingerprint"]["timestamp_utc"]

    if txt1 == txt2 and tr1["raw_symbols"] == tr2["raw_symbols"]:
        print(f"✅ Output deterministic despite timestamp change")
        print(f"   Time 1: {fp1}")
        print(f"   Time 2: {fp2}")
        print(f"   Output identical: {len(txt1)} chars, {len(tr1['raw_symbols'])} symbols")
    else:
        print(f"❌ Determinism broken across timestamps")
        return 1

    print("\n✅ PASS: env_fingerprint tracks platform, output stays deterministic")
    return 0

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