"""
DSS Configuration Management

Secure configuration loading with:
- Environment variables (highest priority)
- .env files
- Default values

Never logs or exposes sensitive values.
"""

import os
from pathlib import Path
from typing import Optional
from dataclasses import dataclass

# Try to load dotenv if available
try:
    from dotenv import load_dotenv
    # Load from multiple possible locations (first found wins)
    project_root = Path(__file__).parent.parent
    env_locations = [
        project_root / ".env",                    # Project root
        project_root / "dss-mvp1" / ".env",       # dss-mvp1 subdirectory
    ]
    for env_path in env_locations:
        if env_path.exists():
            load_dotenv(env_path)
            break
except ImportError:
    pass


@dataclass
class FigmaConfig:
    """Figma API configuration."""
    token: Optional[str] = None
    cache_ttl: int = 300  # 5 minutes

    @classmethod
    def from_env(cls) -> "FigmaConfig":
        return cls(
            token=os.getenv("FIGMA_TOKEN"),
            cache_ttl=int(os.getenv("FIGMA_CACHE_TTL", "300"))
        )

    @property
    def is_configured(self) -> bool:
        return bool(self.token)


@dataclass
class DatabaseConfig:
    """Database configuration."""
    path: str = ".dss/dss.db"

    @classmethod
    def from_env(cls) -> "DatabaseConfig":
        return cls(
            path=os.getenv("DATABASE_PATH", ".dss/dss.db")
        )


@dataclass
class ServerConfig:
    """Server configuration."""
    port: int = 3456
    host: str = "0.0.0.0"
    env: str = "development"
    log_level: str = "info"

    @classmethod
    def from_env(cls) -> "ServerConfig":
        return cls(
            port=int(os.getenv("PORT", "3456")),
            host=os.getenv("HOST", "0.0.0.0"),
            env=os.getenv("NODE_ENV", "development"),
            log_level=os.getenv("LOG_LEVEL", "info")
        )

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


@dataclass
class Config:
    """Main configuration container."""
    figma: FigmaConfig
    database: DatabaseConfig
    server: ServerConfig

    @classmethod
    def load(cls) -> "Config":
        """Load configuration from environment."""
        return cls(
            figma=FigmaConfig.from_env(),
            database=DatabaseConfig.from_env(),
            server=ServerConfig.from_env()
        )

    def summary(self) -> dict:
        """Return config summary (no secrets)."""
        return {
            "figma": {
                "configured": self.figma.is_configured,
                "cache_ttl": self.figma.cache_ttl
            },
            "database": {
                "path": self.database.path
            },
            "server": {
                "port": self.server.port,
                "env": self.server.env,
                "log_level": self.server.log_level
            }
        }


# Global config instance
config = Config.load()


if __name__ == "__main__":
    import json
    print("DSS Configuration:")
    print(json.dumps(config.summary(), indent=2))
