#!/usr/bin/env python3
"""
Memoized config validator - uses @lru_cache.
Profile this to see the lru_cache wrapper overhead.

Usage:
    python3 config_validator_memoized.py
    python3 -m cProfile -s tottime config_validator_memoized.py
"""

import time
from functools import lru_cache

from common import validate_rule_slow, load_events


@lru_cache(maxsize=None)
def validate_rule_cached(rule_id, event_type):
    """Same validation but with caching."""
    return validate_rule_slow(rule_id, event_type)


def process_events(events):
    """Process events using memoized validation."""
    valid_count = 0
    for rule_id, event_type, data in events:
        if validate_rule_cached(rule_id, event_type):
            valid_count += 1
    return valid_count


ITERATIONS = 5


def main():
    events = load_events()
    print(f"Processing {len(events)} events (memoized), {ITERATIONS} iterations...")

    times = []
    for i in range(ITERATIONS):
        if i == 0:
            validate_rule_cached.cache_clear()  # Cold start on first run
        start = time.perf_counter()
        valid_count = process_events(events)
        times.append(time.perf_counter() - start)

    avg = sum(times) / len(times)
    print(f"Valid: {valid_count}")
    print(f"Avg time: {avg:.3f}s")


if __name__ == "__main__":
    main()
