"""Configuration from environment variables."""

from __future__ import annotations

import logging
import os
from dataclasses import dataclass
from urllib.parse import urlparse

logger = logging.getLogger(__name__)


@dataclass(frozen=True)
class Config:
    """Frozen configuration loaded from environment variables."""

    api_key: str
    api_secret: str
    base_url: str | None
    max_order_usd: float
    daily_loss_limit: float
    audit_path: str

    @classmethod
    def from_env(cls) -> Config:
        """Build config from environment variables.

        Raises:
            ValueError: If key/secret are not both set or both absent,
                if numeric values are not positive, or if base_url is invalid.
        """
        api_key = os.environ.get("LIQUID_API_KEY") or None
        api_secret = os.environ.get("LIQUID_API_SECRET") or None

        if api_key is None or api_secret is None:
            raise ValueError(
                "LIQUID_API_KEY and LIQUID_API_SECRET are both required"
            )

        max_order_usd = float(os.environ.get("MAX_ORDER_USD", "1000"))
        daily_loss_limit = float(os.environ.get("DAILY_LOSS_LIMIT", "5000"))

        if max_order_usd <= 0:
            raise ValueError("MAX_ORDER_USD must be > 0")
        if daily_loss_limit <= 0:
            raise ValueError("DAILY_LOSS_LIMIT must be > 0")

        if max_order_usd > daily_loss_limit:
            logger.warning(
                "MAX_ORDER_USD ($%.0f) > DAILY_LOSS_LIMIT ($%.0f). "
                "A single order could exceed the daily loss limit.",
                max_order_usd,
                daily_loss_limit,
            )

        base_url = os.environ.get("LIQUID_BASE_URL") or None
        if base_url is not None:
            parsed = urlparse(base_url)
            if parsed.scheme not in ("http", "https") or not parsed.netloc:
                raise ValueError(
                    f"LIQUID_BASE_URL must be a valid HTTP(S) URL, got: {base_url}"
                )

        audit_path = os.environ.get(
            "LIQUID_MCP_AUDIT_PATH",
            os.path.expanduser("~/.liquidtrading-mcp/trades.jsonl"),
        )
        audit_dir = os.path.dirname(audit_path)
        if audit_dir:
            os.makedirs(audit_dir, exist_ok=True)

        return cls(
            api_key=api_key,
            api_secret=api_secret,
            base_url=base_url,
            max_order_usd=max_order_usd,
            daily_loss_limit=daily_loss_limit,
            audit_path=audit_path,
        )


_config: Config | None = None


def get_config() -> Config:
    """Return a cached Config singleton, creating from env on first call."""
    global _config
    if _config is None:
        _config = Config.from_env()
    return _config


def reset_config() -> None:
    """Reset the config singleton (for testing)."""
    global _config
    _config = None


def set_config(config: Config) -> None:
    """Override the config singleton (for testing)."""
    global _config
    _config = config
