from __future__ import annotations

import os
from dataclasses import dataclass


@dataclass(frozen=True)
class McpConfig:
    url: str
    token: str


@dataclass(frozen=True)
class RuntimeConfig:
    host: str
    port: int
    environment_name: str
    base_url: str
    max_steps: int
    mcp: McpConfig


def load_runtime_config() -> RuntimeConfig:
    return RuntimeConfig(
        host=os.getenv("WEB_AGENT_HOST", "0.0.0.0"),
        port=_number_env("WEB_AGENT_PORT", 5188),
        environment_name=os.getenv("SMQJH_ENVIRONMENT_NAME", "test-gateway"),
        base_url=os.getenv("SMQJH_BASE_URL", "http://192.168.1.242:8080"),
        max_steps=_number_env("SMQJH_AGENT_MAX_STEPS", 6),
        mcp=McpConfig(
            url=_normalize_url(os.getenv("SMQJH_MCP_URL") or os.getenv("MCP_URL") or "http://127.0.0.1:8765/mcp"),
            token=os.getenv("SMQJH_MCP_TOKEN") or os.getenv("MCP_TOKEN") or "",
        ),
    )


def _number_env(key: str, fallback: int) -> int:
    raw = os.getenv(key)
    if not raw:
        return fallback
    try:
        value = int(raw)
    except ValueError:
        return fallback
    return value if value > 0 else fallback


def _normalize_url(value: str) -> str:
    return value.strip().rstrip("/")
