import os
import json
from typing import Any, Optional, List
from pydantic_settings import BaseSettings, SettingsConfigDict
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession

class Settings(BaseSettings):
    # --- General ---
    PROJECT_NAME: str = "Traffic Ecosystem SuperApp"
    VERSION: str = "1.0.0"
    API_V1_STR: str = "/api/v1"
    DEBUG: bool = os.getenv("DEBUG", "False").lower() == "true"

    # --- Security / JWT ---
    # Szigorúan .env-ből!
    SECRET_KEY: str = os.getenv("SECRET_KEY", "NOT_SET_DANGER")
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 7 # 7 nap

    # --- Database & Cache ---
    DATABASE_URL: str = os.getenv("DATABASE_URL")
    REDIS_URL: str = os.getenv("REDIS_URL", "redis://service_finder_redis:6379/0")

    # --- Email (Auto Provider) ---
    EMAIL_PROVIDER: str = os.getenv("EMAIL_PROVIDER", "auto")
    EMAILS_FROM_EMAIL: str = os.getenv("EMAILS_FROM_EMAIL", "info@profibot.hu")
    EMAILS_FROM_NAME: str = "Profibot"
    
    # SMTP & SendGrid (Szigorúan .env-ből)
    SENDGRID_API_KEY: Optional[str] = os.getenv("SENDGRID_API_KEY")
    SMTP_HOST: Optional[str] = os.getenv("SMTP_HOST")
    SMTP_PORT: int = int(os.getenv("SMTP_PORT", 587))
    SMTP_USER: Optional[str] = os.getenv("SMTP_USER")
    SMTP_PASSWORD: Optional[str] = os.getenv("SMTP_PASSWORD")

    # --- External URLs ---
    # .env-ben legyen átírva a .10-es IP-re!
    FRONTEND_BASE_URL: str = os.getenv("FRONTEND_BASE_URL", "http://localhost:3000")

    # --- Dinamikus Admin Motor ---
    async def get_db_setting(self, db: AsyncSession, key_name: str, default: Any = None) -> Any:
        """
        Lekéri a paramétert a data.system_settings táblából.
        Ezzel érjük el, hogy a kód újraírása nélkül, adminból lehessen 
        állítani a jutalom napokat, százalékokat, stb.
        """
        try:
            query = text("SELECT value_json FROM data.system_settings WHERE key_name = :key")
            result = await db.execute(query, {"key": key_name})
            row = result.fetchone()
            if row and row[0] is not None:
                return row[0]
            return default
        except Exception:
            return default

    # .env fájl konfigurációja
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=True,
        extra="ignore"
    )


settings = Settings()