"""
GeoEdu Service Configuration
Environment-based configuration with Pydantic Settings
"""
from functools import lru_cache
from typing import Optional
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """Application settings loaded from environment variables."""

    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
    )

    # Service Config
    port: int = 8088
    environment: str = "development"
    debug: bool = False

    # JWT Authentication
    jwt_secret: str = "your-super-secret-jwt-key"
    jwt_algorithm: str = "HS256"
    jwt_expiration_hours: int = 24

    # PostgreSQL (PostGIS)
    database_url: str = "postgresql+asyncpg://breakpilot:breakpilot123@postgres:5432/breakpilot_db"

    # MinIO (S3-compatible storage)
    minio_endpoint: str = "minio:9000"
    minio_access_key: str = "breakpilot"
    minio_secret_key: str = "breakpilot123"
    minio_bucket: str = "breakpilot-geo"
    minio_secure: bool = False

    # Ollama (LLM for learning nodes)
    ollama_base_url: str = "http://host.docker.internal:11434"
    ollama_model: str = "qwen2.5:14b"
    ollama_timeout: int = 120

    # Data Directories
    osm_data_dir: str = "/app/data/osm"
    dem_data_dir: str = "/app/data/dem"
    tile_cache_dir: str = "/app/cache/tiles"
    bundle_dir: str = "/app/bundles"

    # Tile Server Config
    default_pmtiles_file: str = "germany.pmtiles"
    tile_cache_max_size_gb: float = 50.0

    # DEM Config
    dem_resolution: str = "GLO-30"  # 30m Copernicus DEM
    terrain_tile_size: int = 256

    # AOI Limits (DSGVO data minimization)
    max_aoi_size_km2: float = 4.0  # Max 4 km² per AOI
    max_aoi_per_user: int = 10
    aoi_retention_days: int = 30  # Auto-delete after 30 days

    # Learning Nodes
    max_nodes_per_aoi: int = 20
    supported_themes: list[str] = [
        "topographie",
        "landnutzung",
        "orientierung",
        "geologie",
        "hydrologie",
        "vegetation",
    ]

    # CORS (for frontend access)
    cors_origins: list[str] = [
        "http://localhost:3000",
        "http://localhost:3001",
        "http://localhost:8088",
    ]

    @property
    def pmtiles_path(self) -> str:
        """Full path to PMTiles file."""
        return f"{self.osm_data_dir}/{self.default_pmtiles_file}"

    @property
    def is_development(self) -> bool:
        """Check if running in development mode."""
        return self.environment == "development"


@lru_cache
def get_settings() -> Settings:
    """Get cached settings instance."""
    return Settings()


# Export settings instance for convenience
settings = get_settings()
