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

class Settings(BaseSettings):
    # --- Paths ---
    BASE_DIR: Path = Path(__file__).resolve().parent.parent.parent
    STATIC_DIR: str = os.path.join(str(BASE_DIR), "static")

    # --- General ---
    PROJECT_NAME: str = "Service Finder Ecosystem"
    VERSION: str = "2.1.0"
    API_V1_STR: str = "/api/v1"
    DEBUG: bool = False

    # --- Security / JWT ---
    SECRET_KEY: str = "NOT_SET_DANGER"
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 
    REFRESH_TOKEN_EXPIRE_DAYS: int = 7

    # --- Initial Admin ---
    INITIAL_ADMIN_EMAIL: str = "admin@servicefinder.hu"
    INITIAL_ADMIN_PASSWORD: str = "Admin123!"

    # --- Database & Cache ---
    DATABASE_URL: str
    REDIS_URL: str = "redis://service_finder_redis:6379/0"

    # --- Email ---
    EMAIL_PROVIDER: str = "auto"
    EMAILS_FROM_EMAIL: str = "info@profibot.hu"
    EMAILS_FROM_NAME: str = "Profibot"
    
    SENDGRID_API_KEY: Optional[str] = None
    SMTP_HOST: Optional[str] = None
    SMTP_PORT: int = 587
    SMTP_USER: Optional[str] = None
    SMTP_PASSWORD: Optional[str] = None

    # --- External URLs ---
    FRONTEND_BASE_URL: str = "https://dev.profibot.hu"

    # --- Google OAuth ---
    GOOGLE_CLIENT_ID: str = ""
    GOOGLE_CLIENT_SECRET: str = ""
    GOOGLE_CALLBACK_URL: str = "https://dev.profibot.hu/api/v1/auth/callback/google"

    # --- Brute-Force & Security ---
    LOGIN_RATE_LIMIT_ANON: str = "5/minute"
    AUTH_MIN_PASSWORD_LENGTH: int = 8

    # --- Dinamikus Admin Motor (Javított) ---
    async def get_db_setting(self, db: AsyncSession, key_name: str, default: Any = None) -> Any:
        """
        Lekér egy beállítást a data.system_parameters táblából.
        Ha a tábla még nem létezik (migráció előtt), elkapja a hibát és default-ot ad.
        """
        try:
            # A lekérdezés a system_parameters táblát és a 'key' mezőt használja
            query = text("SELECT value FROM data.system_parameters WHERE key = :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:
            # Adatbázis hiba vagy hiányzó tábla esetén fallback az alapértelmezett értékre
            return default

    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=True,
        extra="ignore"
    )

settings = Settings()