"""Centralized environment configuration for Maeris MCP.

Switch environments via the MAERIS_ENV environment variable:

    MAERIS_ENV=prod   →  production (default)
    MAERIS_ENV=dev    →  dev Railway deployment
    MAERIS_ENV=local  →  localhost backend + frontend

Individual URLs can still be overridden on top of the selected env:

    MAERIS_API_URL    →  override service_url  (Maeris API / mirabilis)
    MAERIS_APP_URL    →  override app_url      (Maeris App / light)
"""

from __future__ import annotations

import os
from dataclasses import dataclass


@dataclass(frozen=True)
class EnvConfig:
    name: str
    service_url: str  # Maeris API / mirabilis backend
    app_url: str      # Maeris App / light frontend


DEV = EnvConfig(
    name="dev",
    service_url="https://mirabilis-dev.up.railway.app",
    app_url="https://light-dev.up.railway.app",
)

LOCAL = EnvConfig(
    name="local",
    service_url="http://127.0.0.1:5001",
    app_url="http://localhost:3000",
)

PROD = EnvConfig(
    name="prod",
    service_url="https://mirabilis-production.up.railway.app",
    app_url="https://light.maeris.io",
)

_ENVS: dict[str, EnvConfig] = {
    "dev": DEV,
    "local": LOCAL,
    "prod": PROD,
    "production": PROD,
}


def _resolve() -> EnvConfig:
    env_name = os.getenv("MAERIS_ENV", "").strip().lower()
    base = _ENVS.get(env_name, PROD)

    # Per-URL overrides take precedence over the selected env
    service_url = os.getenv("MAERIS_API_URL", base.service_url)
    app_url = os.getenv("MAERIS_APP_URL", base.app_url)

    if service_url == base.service_url and app_url == base.app_url:
        return base
    return EnvConfig(name=base.name, service_url=service_url, app_url=app_url)


#: Resolved environment — import this everywhere instead of os.getenv.
ENV: EnvConfig = _resolve()
