from pydantic_settings import BaseSettings, SettingsConfigDict
from sqlalchemy.engine import URL as SAUrl


class Settings(BaseSettings):
    APP_NAME: str = "Configurable LMS Backend"
    ENV: str = "development"

    # ─── MySQL Database components ────────────────────────────────────────────
    DB_HOST: str = "127.0.0.1"
    DB_HOST_READONLY: str = "127.0.0.1"
    DB_PORT: int = 3306
    DB_DATABASE: str = "lms_db"
    DB_USERNAME: str = "root"
    DB_PASSWORD: str = ""
    DB_POOL_SIZE: int = 10
    DB_MAX_OVERFLOW: int = 20
    DB_POOL_RECYCLE: int = 3600

    # ─── Redis ────────────────────────────────────────────────────────────────
    REDIS_HOST: str = "localhost"
    REDIS_PORT: int = 6379
    REDIS_DB: int = 0
    REDIS_CACHE_TTL_SECONDS: int = 3600

    # ─── CORS ────────────────────────────────────────────────────────────────
    CORS_ORIGINS: str = "http://localhost:5173"

    # ─── JWT Authentication ───────────────────────────────────────────────────
    JWT_SECRET_KEY: str = "change-me-in-production"
    JWT_ALGORITHM: str = "HS256"
    JWT_EXPIRE_MINUTES: int = 480  # 8 hours (production-friendly)

    # ─── Admin Credentials (API / emergency access only) ─────────────────────
    ADMIN_USERNAME: str = "admin"
    ADMIN_PASSWORD: str = "admin123"

    # ─── Microsoft Entra ID (Azure AD) OAuth2 ────────────────────────────────
    OAUTH_APP_ID: str = ""            # Azure Application (client) ID
    OAUTH_APP_SECRET: str = ""        # Azure client secret value
    OAUTH_TENANT_ID: str = ""         # Azure Directory (tenant) ID
    OAUTH_REDIRECT_URI: str = "http://localhost:5173/auth/callback"
    OAUTH_ALLOWED_DOMAIN: str = "creditfair.in"   # Only this domain may log in
    OAUTH_SCOPES: str = "openid profile email User.Read"

    model_config = SettingsConfigDict(env_file=".env", extra="ignore")

    @property
    def database_url(self) -> SAUrl:
        """Builds a SQLAlchemy URL safely — handles special chars in password."""
        return SAUrl.create(
            drivername="mysql+aiomysql",
            username=self.DB_USERNAME,
            password=self.DB_PASSWORD,
            host=self.DB_HOST,
            port=self.DB_PORT,
            database=self.DB_DATABASE,
            query={"charset": "utf8mb4"},
        )

    @property
    def cors_origins_list(self) -> list[str]:
        """Parses comma-separated CORS_ORIGINS into a list."""
        return [o.strip() for o in self.CORS_ORIGINS.split(",") if o.strip()]

    @property
    def oauth_scopes_list(self) -> list[str]:
        """Parses space-separated OAUTH_SCOPES into a list."""
        return [s.strip() for s in self.OAUTH_SCOPES.split() if s.strip()]

    @property
    def is_production(self) -> bool:
        return self.ENV.lower() == "production"


settings = Settings()

