from functools import lru_cache
from typing import Literal
import base64
from pydantic import Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        extra="ignore",
    )

    # General
    APP_NAME: str = "Telegram SaaS Platform"
    APP_ENV: Literal["development", "staging", "production", "testing"] = "development"
    APP_DEBUG: bool = False
    APP_SECRET_KEY: str = Field(min_length=32)
    API_V1_PREFIX: str = "/api/v1"

    # Database
    DATABASE_URL: str = "postgresql+asyncpg://telegram_saas:saas_secret_password_2026@127.0.0.1:5432/telegram_saas"
    DATABASE_POOL_SIZE: int = 20
    DATABASE_MAX_OVERFLOW: int = 10
    DATABASE_ECHO: bool = False

    # Cache & Queues
    REDIS_URL: str = "redis://127.0.0.1:6379/0"
    CELERY_BROKER_URL: str = "redis://127.0.0.1:6379/1"
    CELERY_RESULT_BACKEND: str = "redis://127.0.0.1:6379/2"

    # Security & JWT
    JWT_SECRET_KEY: str = Field(min_length=32)
    JWT_ALGORITHM: str = "HS256"
    JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 15
    JWT_REFRESH_TOKEN_EXPIRE_DAYS: int = 7

    # Encryption (AES-256-GCM)
    ENCRYPTION_KEY: str = Field(description="Base64 encoded 32-byte key for AES-256-GCM")
    ENCRYPTION_KEY_VERSION: int = 1

    # Telegram
    TELEGRAM_WEBHOOK_BASE_URL: str = "https://localhost:8000/webhooks/telegram"
    TELEGRAM_BOT_TOKEN: str = "7182910392:AAExampleBotTokenForVerification2026"
    TELEGRAM_BOT_USERNAME: str = "astraea_super_bot"
    TELEGRAM_AUTH_MAX_AGE_SECONDS: int = 86400  # 24 hours anti-replay threshold

    # Optional / Integrations
    SENTRY_DSN: str | None = None
    RAZORPAY_KEY_ID: str | None = "rzp_test_placeholder"
    RAZORPAY_KEY_SECRET: str | None = "rzp_secret_placeholder"
    RAZORPAY_WEBHOOK_SECRET: str | None = "rzp_webhook_secret_placeholder"
    STRIPE_SECRET_KEY: str | None = "sk_test_placeholder"
    STRIPE_WEBHOOK_SECRET: str | None = "whsec_test_placeholder"
    OPENROUTER_API_KEY: str | None = None
    OPENAI_API_KEY: str | None = None

    @field_validator("ENCRYPTION_KEY")
    @classmethod
    def validate_encryption_key(cls, v: str) -> str:
        try:
            raw = base64.b64decode(v)
            if len(raw) != 32:
                raise ValueError("ENCRYPTION_KEY must be exactly 32 bytes when base64 decoded.")
        except Exception as exc:
            raise ValueError(f"Invalid ENCRYPTION_KEY: {exc}") from exc
        return v

    @property
    def raw_encryption_key(self) -> bytes:
        return base64.b64decode(self.ENCRYPTION_KEY)


@lru_cache()
def get_settings() -> Settings:
    return Settings()
