"""Configuration for Edge SDK."""

from __future__ import annotations

import os


class EdgeConfig:
    """Configuration for the Edge SDK.

    Reads from constructor params, then falls back to environment variables.

    Env vars:
        EDGE_BASE_URL  — market-data-service base URL
        EDGE_API_KEY   — API key sent as X-API-Key header

    Legacy env vars (also checked as fallback):
        MARKET_DATA_API_BASE_URL — if set, the ``/api/v1`` suffix is stripped
                                   automatically so it works as a base URL.

    Default: Edge's hosted market data service (no env var needed).
    """

    DEFAULT_TIMEOUT = 120.0

    def __init__(
        self,
        base_url: str | None = None,
        api_key: str | None = None,
        timeout: float = DEFAULT_TIMEOUT,
    ):
        self.base_url = self._resolve_base_url(base_url)
        self.api_key = api_key or os.environ.get("EDGE_API_KEY", "")
        self.timeout = timeout

    @staticmethod
    def _resolve_base_url(explicit: str | None) -> str:
        if explicit:
            return explicit.rstrip("/")
        # Primary env var
        url = os.environ.get("EDGE_BASE_URL", "")
        if url:
            return url.rstrip("/")
        # Legacy: MARKET_DATA_API_BASE_URL may include /api/v1 suffix
        legacy = os.environ.get("MARKET_DATA_API_BASE_URL", "")
        if legacy:
            legacy = legacy.rstrip("/")
            if legacy.endswith("/api/v1"):
                legacy = legacy[: -len("/api/v1")]
            return legacy
        return "https://market-data-api-dev-730192956959.us-central1.run.app"

    @property
    def api_url(self) -> str:
        """Full base URL including the ``/api/v1`` prefix."""
        return f"{self.base_url}/api/v1"

    @property
    def headers(self) -> dict[str, str]:
        """Default headers for every request."""
        h: dict[str, str] = {
            "Accept": "application/json",
            "User-Agent": "edge-sdk/1.0.1",
        }
        if self.api_key:
            h["X-API-Key"] = self.api_key
        return h
