"""
Configuration loader for Public Web Frontend

Loads environment-specific configuration from YAML files.
"""

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


logger = structlog.get_logger(__name__)


@dataclass
class ServerConfig:
    """Server configuration settings."""
    host: str
    port: int
    debug: bool
    workers: int = 4


@dataclass
class APIConfig:
    """API backend configuration."""
    base_url: str
    timeout: int = 30
    verify_ssl: bool = True


@dataclass
class SessionConfig:
    """Session configuration."""
    lifetime_hours: int
    cookie_secure: bool
    cookie_httponly: bool
    cookie_samesite: str


@dataclass
class Config:
    """Main configuration object."""
    server: ServerConfig
    api: APIConfig
    session: SessionConfig
    environment: str


def load_config(environment: Optional[str] = None) -> Config:
    """
    Load configuration from YAML file.

    Args:
        environment: Environment name (development, production). If None, uses FLASK_ENV env var.

    Returns:
        Config object with all settings.
    """
    if environment is None:
        environment = os.getenv("FLASK_ENV", "development")

    config_dir = Path(__file__).parent.parent / "config"
    config_path = config_dir / f"{environment}.yaml"

    if not config_path.exists():
        raise FileNotFoundError(f"Configuration file not found: {config_path}")

    with open(config_path, 'r') as f:
        data = yaml.safe_load(f)

    config = Config(
        server=ServerConfig(**data['server']),
        api=APIConfig(**data['api']),
        session=SessionConfig(**data['session']),
        environment=environment
    )

    logger.info("config_loaded",
                environment=environment,
                api_url=config.api.base_url,
                server_port=config.server.port)

    return config
