"""Server configuration."""

import os
from dataclasses import dataclass, field


def _env_bool(name: str, default: bool = False) -> bool:
    """Parse a boolean environment variable."""
    value = os.environ.get(name)
    if value is None:
        return default
    return value.strip().lower() in {"1", "true", "yes", "on"}


def _env_int(name: str, default: int) -> int:
    """Parse an integer environment variable."""
    value = os.environ.get(name)
    if value is None:
        return default
    try:
        return int(value.strip())
    except ValueError:
        return default


def _get_cors_origins() -> list[str]:
    """Build the CORS allowed origins list.

    Priority:
    1. IEUM_CORS_ORIGINS environment variable (comma-separated)
    2. Restrictive defaults (localhost only)
    """
    env_origins = os.environ.get("IEUM_CORS_ORIGINS")
    if env_origins:
        return [o.strip() for o in env_origins.split(",") if o.strip()]

    # Restrictive defaults -- localhost only
    return [
        "http://localhost:3000",
        "http://localhost:8765",
        "http://127.0.0.1:3000",
        "http://127.0.0.1:8765",
    ]


@dataclass
class ServerConfig:
    """Configuration for the API server."""

    host: str = "127.0.0.1"
    port: int = 8765
    cors_origins: list[str] = field(default_factory=_get_cors_origins)
    debug: bool = False
    reload: bool = False
    log_level: str = "info"

    # Working directory for file operations
    working_directory: str | None = None
    # If true, prevent loopback-only bind for centralized remote deployment.
    remote_only: bool = _env_bool("IEUM_REMOTE_ONLY", False)
    # Optional sandbox root. When set, sessions are constrained to:
    #   <sandbox_root>/<user_id>/<workspace_id>/...
    sandbox_root: str | None = os.environ.get("IEUM_SANDBOX_ROOT")

    # Session settings
    session_timeout_minutes: int = 60
    max_sessions: int = 100
    max_sessions_per_user: int = _env_int("IEUM_MAX_SESSIONS_PER_USER", 0)
    default_approval_policy: str = os.environ.get("IEUM_APPROVAL_POLICY_DEFAULT", "manual")
    session_policy_file: str | None = os.environ.get("IEUM_SESSION_POLICY_FILE")
    session_rate_limit_max_requests: int = _env_int("IEUM_SESSION_RATE_LIMIT_MAX_REQUESTS", 0)
    session_rate_limit_window_seconds: int = _env_int("IEUM_SESSION_RATE_LIMIT_WINDOW_SECONDS", 60)

    # Require explicit user identity in header/query (multi-tenant mode)
    require_user_identity: bool = _env_bool("IEUM_REQUIRE_USER_ID", False)

    # Rate-limit settings
    rate_limit_enabled: bool = _env_bool("IEUM_RATE_LIMIT_ENABLED", True)
    rate_limit_max_requests: int = _env_int("IEUM_RATE_LIMIT_MAX_REQUESTS", 120)
    rate_limit_window_seconds: int = _env_int("IEUM_RATE_LIMIT_WINDOW_SECONDS", 60)

    # TLS settings
    tls_required: bool = _env_bool("IEUM_TLS_REQUIRED", False)
    trust_proxy_tls: bool = _env_bool("IEUM_TRUST_PROXY_TLS", False)
    ssl_certfile: str | None = os.environ.get("IEUM_SSL_CERTFILE")
    ssl_keyfile: str | None = os.environ.get("IEUM_SSL_KEYFILE")

    # WebSocket settings
    ws_ping_interval: float = 30.0
    ws_ping_timeout: float = 10.0


# Default server configuration
default_config = ServerConfig()
