"""
Test quota schema integrity to guard against legacy KeyError regressions.
"""
from src.fmatch.saas.middleware.quota_checker import TIER_LIMITS, UsageQuota


def test_tier_limits_have_required_keys():
    """All tiers must expose the base keys expected by quota middleware."""
    required_keys = [
        "monthly_rows",
        "enrichment_credits",
        "max_schedules",
        "allowed_frequencies",
        "grace_percentage",
    ]

    for tier_name, limits in TIER_LIMITS.items():
        for key in required_keys:
            assert key in limits, f"Tier '{tier_name}' missing required key '{key}'"


def test_quota_v2_keys_present():
    """Ensure Quota V2 feature switches exist for every tier."""
    quota_v2_keys = [
        "concurrent_jobs",
        "candidate_cap",
        "require_b2c",
        "allow_advanced_algos",
    ]

    for tier_name, limits in TIER_LIMITS.items():
        for key in quota_v2_keys:
            assert key in limits, f"Tier '{tier_name}' missing quota v2 key '{key}'"


def test_no_legacy_daily_keys():
    """Legacy daily_* keys must stay removed to avoid schema drift."""
    legacy_keys = ["daily_runs", "daily_rows"]

    for tier_name, limits in TIER_LIMITS.items():
        for key in legacy_keys:
            assert key not in limits, f"Tier '{tier_name}' unexpectedly includes '{key}'"


def test_usage_quota_get_limits_no_keyerror():
    """UsageQuota.get_limits should remain resilient for all tiers."""
    for tier_name in TIER_LIMITS.keys():
        quota = UsageQuota(
            account_id="test",
            tier=tier_name,
            monthly_rows_used=100,
            enrichment_credits_used=0,
        )

        limits = quota.get_limits()
        assert "monthly_rows" in limits
        assert "enrichment_credits" in limits
