from __future__ import annotations

"""Lightweight wrapper around Stripe configuration used by the GUI."""

import os
from dataclasses import dataclass
from typing import Dict


CHECKOUT_BASE_URL = "https://checkout.stripe.com"


_PRICE_IDS: Dict[tuple[str, str], str] = {
    ("pro", "monthly"): "price_pro_monthly",
    ("pro", "annual"): "price_pro_annual",
    ("enterprise", "monthly"): "price_enterprise_monthly",
    ("enterprise", "annual"): "price_enterprise_annual",
}


@dataclass
class StripeClient:
    """Encapsulate Stripe configuration."""

    test_mode: bool = False
    api_key: str | None = None

    def __post_init__(self) -> None:
        if not self.api_key:
            self.api_key = self._resolve_api_key()

    def is_configured(self) -> bool:
        """Return True if an API key is present."""
        return bool(self.api_key)

    def create_checkout_session(self, tier: str, cadence: str) -> Dict[str, str]:
        """Return a mocked checkout session description."""
        self._ensure_configured()
        price_id = self._resolve_price_id(tier, cadence)
        suffix = "test/" if self.test_mode else ""
        return {
            "url": f"{CHECKOUT_BASE_URL}/{suffix}{price_id}",
            "mode": "subscription",
            "price_id": price_id,
        }

    def _resolve_api_key(self) -> str | None:
        env_var = "STRIPE_TEST_KEY" if self.test_mode else "STRIPE_LIVE_KEY"
        return os.getenv(env_var)

    def _ensure_configured(self) -> None:
        if not self.is_configured():
            raise RuntimeError("Stripe client is not configured with an API key.")

    @staticmethod
    def _resolve_price_id(tier: str, cadence: str) -> str:
        try:
            return _PRICE_IDS[(tier.lower(), cadence.lower())]
        except KeyError as exc:
            raise ValueError(f"Unsupported price combination: {tier}/{cadence}") from exc
