"""
Pricing & Tier Configuration

Central source of truth for all license tiers, pricing, and feature gates.
Update prices and features here — everything else reads from this file.

Two separate concerns:
- FEATURE_FLAGS: enforced in code, only enterprise-only features listed
- TIERS: full tier config including marketing features for pricing page display
"""

# ─────────────────────────────────────────────────────────────────────
# FEATURE FLAGS — all features enabled (single enterprise license)
# ─────────────────────────────────────────────────────────────────────

FEATURE_FLAGS = {
    "enterprise": {
        "ci_cd_pipeline": True,
        "csv_export":     True,
        "json_export":    True,
        "sarif_export":   True,
    },
}

# ─────────────────────────────────────────────────────────────────────
# TIERS — full config including pricing and marketing features
# ─────────────────────────────────────────────────────────────────────

TIERS = {
    "enterprise": {
        "display_name": "Enterprise",
        "price_monthly": None,      # Contact sales
        "price_annual": None,       # Contact sales
        "currency": "USD",
        "trial_days": 0,
        "max_seats": None,          # Custom (negotiated per deal)
        "features": FEATURE_FLAGS["enterprise"],
        "marketing_features": [
            "Everything in Professional",
            "CSV / JSON / SARIF export",
            "On-premise & air-gapped deployment",
            "Custom AI provider (on-premise LLM)",
            "Volume pricing",
            "Priority support with SLA",
        ],
        "limits": {
            "scans_per_day": None,  # Unlimited
        },
        "description": "Unlimited analysis with CI/CD integration and enterprise exports",
    },
}

# Trial = Professional features with 14-day expiry (no separate tier needed)


# ─────────────────────────────────────────────────────────────────────
# Helper functions
# ─────────────────────────────────────────────────────────────────────

def get_tier(tier_name: str) -> dict:
    return TIERS.get(tier_name, TIERS["enterprise"])


def get_features_for_tier(tier_name: str) -> dict:
    return FEATURE_FLAGS.get(tier_name, FEATURE_FLAGS["enterprise"])


def is_feature_enabled(tier_name: str, feature_name: str) -> bool:
    return get_features_for_tier(tier_name).get(feature_name, False)


def get_tier_limit(tier_name: str, limit_name: str) -> int | None:
    limits = get_tier(tier_name).get("limits", {})
    return limits.get(limit_name)


def create_purchase_snapshot(tier_name: str, billing_interval: str, promotion_code: str | None = None, discount_pct: float = 0.0) -> dict:
    from datetime import datetime, timedelta, timezone

    tier = get_tier(tier_name)

    base_price = tier.get("price_annual") if billing_interval == "annual" else tier.get("price_monthly")
    original_price = base_price
    if base_price is not None and discount_pct > 0:
        base_price = round(base_price * (1 - discount_pct / 100), 2)

    now = datetime.now(timezone.utc)
    if tier_name == "professional" and billing_interval == "trial":
        validity_end = now + timedelta(days=14)
    elif billing_interval == "annual":
        validity_end = now + timedelta(days=365)
    elif billing_interval == "monthly":
        validity_end = now + timedelta(days=30)
    else:
        validity_end = None

    return {
        "tier": tier_name,
        "billing_interval": billing_interval,
        "price_at_purchase": base_price,
        "original_price": original_price if discount_pct > 0 else None,
        "currency": tier.get("currency", "USD"),
        "promotion_code": promotion_code,
        "validity_start": now.isoformat(),
        "validity_end": validity_end.isoformat() if validity_end else None,
        "features": get_features_for_tier(tier_name),
        "limits": tier.get("limits", {}),
        "max_seats": tier.get("max_seats"),
    }


def get_all_tiers_for_display() -> list:
    result = []
    for tier_name, tier in TIERS.items():
        result.append({
            "id": tier_name,
            "name": tier["display_name"],
            "price_monthly": tier["price_monthly"],
            "price_annual": tier["price_annual"],
            "currency": tier["currency"],
            "description": tier["description"],
            "max_seats": tier["max_seats"],
            "features": tier["features"],
            "marketing_features": tier["marketing_features"],
        })
    return result
