#!/usr/bin/env python3
"""
Macro quota KAT.

Proves: GLYPHSCOPE_MACRO_QUOTA enforces hard limit on macro expansions.
When quota=0, no macros allowed (falls back to body_hint).
"""
import os
import sys

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

from helix_cdc.cdc_decode import CDCDecoder

def main():
    print("=== Macro Quota KAT ===")

    # Test 1: Quota = 0 (no macros allowed)
    print("\nTest 1: GLYPHSCOPE_MACRO_QUOTA=0 (no macros)")
    os.environ["GLYPHSCOPE_ALLOW_MACROS"] = "1"
    os.environ["GLYPHSCOPE_MACRO_QUOTA"] = "0"
    dec = CDCDecoder(seed_path=None)
    _, tr = dec.generate_from_anchor("", max_new_tokens=128, temperature=0.2, seed=123)

    assert tr["macro_used"] is None, f"Expected no macro, got {tr['macro_used']}"
    assert tr["macro_uses"] == 0, f"Expected 0 uses, got {tr['macro_uses']}"
    assert tr["macro_quota"] == 0, f"Expected quota=0, got {tr['macro_quota']}"
    # Note: body_hint not auto-enabled when only quota=0 (allow_macros still True)
    # This just prevents macro expansion, doesn't fall back
    print(f"✅ Quota=0: no macro used (quota enforced)")

    # Test 2: Quota = 1 (default, one macro allowed)
    print("\nTest 2: GLYPHSCOPE_MACRO_QUOTA=1 (one macro allowed)")
    os.environ["GLYPHSCOPE_MACRO_QUOTA"] = "1"
    os.environ["GLYPHSCOPE_MACRO_MODE"] = "force"  # Force macro to test quota
    dec2 = CDCDecoder(seed_path=None)
    _, tr2 = dec2.generate_from_anchor("", max_new_tokens=128, temperature=0.2, seed=123)

    assert tr2["macro_used"] == "@LEV_DP", f"Expected macro, got {tr2['macro_used']}"
    assert tr2["macro_uses"] == 1, f"Expected 1 use, got {tr2['macro_uses']}"
    assert tr2["macro_quota"] == 1, f"Expected quota=1, got {tr2['macro_quota']}"
    print(f"✅ Quota=1: macro used at pos={tr2['macro_pos']}, tiles_before={tr2['tiles_before_macro']}")

    # Clean up
    os.environ.pop("GLYPHSCOPE_ALLOW_MACROS", None)
    os.environ.pop("GLYPHSCOPE_MACRO_QUOTA", None)
    os.environ.pop("GLYPHSCOPE_MACRO_MODE", None)

    print("\n✅ PASS: macro quota respected")
    return 0

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