"""
Server configuration for Brace Generator API.
"""
import os
from pathlib import Path


class Config:
    """Server configuration loaded from environment variables."""
    
    # Server settings (DEV uses port 8001)
    HOST: str = os.getenv("HOST", "0.0.0.0")
    PORT: int = int(os.getenv("PORT", "8001"))
    DEBUG: bool = os.getenv("DEBUG", "true").lower() == "true"
    
    # Model settings
    DEVICE: str = os.getenv("DEVICE", "cuda")  # 'cuda' or 'cpu'
    MODEL: str = os.getenv("MODEL", "scoliovis")  # 'scoliovis' or 'vertebra-landmark'
    
    # Paths
    BASE_DIR: Path = Path(__file__).parent.parent
    TEMPLATES_DIR: Path = BASE_DIR / "rigoBrace(2)"
    WEIGHTS_DIR: Path = BASE_DIR.parent / "scoliovis-api" / "models"
    
    # TEMP_DIR: Use system temp on Windows, /tmp on Linux
    @staticmethod
    def _get_temp_dir() -> Path:
        env_temp = os.getenv("TEMP_DIR")
        if env_temp:
            return Path(env_temp)
        # Use system temp directory (works on both Windows and Linux)
        import tempfile
        return Path(tempfile.gettempdir()) / "brace_generator"
    
    TEMP_DIR: Path = _get_temp_dir()
    
    # CORS
    CORS_ORIGINS: list = os.getenv("CORS_ORIGINS", "*").split(",")
    
    # Request limits
    MAX_IMAGE_SIZE_MB: int = int(os.getenv("MAX_IMAGE_SIZE_MB", "50"))
    REQUEST_TIMEOUT_SECONDS: int = int(os.getenv("REQUEST_TIMEOUT_SECONDS", "120"))
    
    @classmethod
    def ensure_dirs(cls):
        """Create necessary directories."""
        cls.TEMP_DIR.mkdir(parents=True, exist_ok=True)
    
    @classmethod
    def get_device(cls) -> str:
        """Get device, falling back to CPU if CUDA unavailable."""
        import torch
        if cls.DEVICE == "cuda" and torch.cuda.is_available():
            return "cuda"
        return "cpu"


config = Config()
