from __future__ import annotations

import os
from dataclasses import dataclass, field
from typing import Literal

TransportMode = Literal["http", "stdio"]

_transport_mode: TransportMode = "http"


def set_transport_mode(mode: TransportMode) -> None:
    global _transport_mode
    _transport_mode = mode


def get_transport_mode() -> TransportMode:
    return _transport_mode


def _optional_env(name: str, fallback: str) -> str:
    val = (os.environ.get(name) or "").strip()
    return val if val else fallback


def _number_env(name: str, fallback: int) -> int:
    raw = os.environ.get(name)
    if not raw:
        return fallback
    try:
        parsed = int(raw)
        return parsed if parsed > 0 else fallback
    except ValueError:
        return fallback


@dataclass(frozen=True)
class ThrottleConfig:
    upload_window_ms: int = 15 * 60 * 1000
    upload_max_requests: int = 30
    status_window_ms: int = 15 * 60 * 1000
    status_max_requests: int = 120
    download_url_window_ms: int = 15 * 60 * 1000
    download_url_max_requests: int = 60


@dataclass(frozen=True)
class WaitConfig:
    max_concurrent: int = 50
    max_duration_ms: int = 120_000
    poll_initial_ms: int = 2_000
    poll_max_ms: int = 8_000
    poll_backoff_factor: float = 1.5


@dataclass(frozen=True)
class SessionConfig:
    max_total: int = 1000
    max_per_token: int = 50
    idle_timeout_ms: int = 5 * 60 * 1000


@dataclass(frozen=True)
class McpConfig:
    api_base_url: str = ""
    port: int = 8082
    allowed_origins: list[str] = field(default_factory=list)
    log_level: str = "info"
    max_file_size_bytes: int = 5 * 1024 * 1024
    api_timeout_ms: int = 60_000
    metrics_token: str = ""
    throttle: ThrottleConfig = field(default_factory=ThrottleConfig)
    wait: WaitConfig = field(default_factory=WaitConfig)
    session: SessionConfig = field(default_factory=SessionConfig)


def _build_config() -> McpConfig:
    origins_raw = _optional_env("MCP_ALLOWED_ORIGINS", "")
    origins = [o.strip() for o in origins_raw.split(",") if o.strip()]

    return McpConfig(
        api_base_url=_optional_env(
            "AGENTVEE_API_BASE_URL",
            "https://agentvee-api-develop.fly.dev",
        ).rstrip("/"),
        port=_number_env("MCP_PORT", 8082),
        allowed_origins=origins,
        log_level=_optional_env("MCP_LOG_LEVEL", "info"),
        max_file_size_bytes=5 * 1024 * 1024,
        api_timeout_ms=_number_env("MCP_API_TIMEOUT_MS", 60_000),
        metrics_token=_optional_env("MCP_METRICS_TOKEN", ""),
        throttle=ThrottleConfig(),
        wait=WaitConfig(
            max_concurrent=_number_env("MCP_WAIT_MAX_CONCURRENT", 50),
            max_duration_ms=_number_env("MCP_WAIT_MAX_DURATION_MS", 120_000),
            poll_initial_ms=_number_env("MCP_WAIT_POLL_INITIAL_MS", 2_000),
            poll_max_ms=_number_env("MCP_WAIT_POLL_MAX_MS", 8_000),
        ),
        session=SessionConfig(
            max_total=_number_env("MCP_SESSION_MAX_TOTAL", 1000),
            max_per_token=_number_env("MCP_SESSION_MAX_PER_TOKEN", 50),
            idle_timeout_ms=_number_env("MCP_SESSION_IDLE_TIMEOUT_MS", 5 * 60 * 1000),
        ),
    )


mcp_config = _build_config()
