import os

class Config:
    api_key = None
    service_name = None
    environment = None
    platform_url = None
    base_url = None           # explicit override via AIOPS_SERVICE_BASE_URL env var
    _detected_base_url = None # auto-detected from first Flask request (Host header)

    @classmethod
    def get_base_url(cls):
        """
        Return the service's own base URL for platform callback (client fixer).

        Priority:
          1. AIOPS_SERVICE_BASE_URL env var — explicit operator override
          2. Auto-detected from the first Flask request Host header
          3. None — heartbeat sent without base_url, fixer won't auto-register
        """
        return cls.base_url or cls._detected_base_url

def load_config(api_key=None):
    # Strip whitespace from every string value — prevents silent failures when
    # env vars or arguments contain accidental leading/trailing spaces.
    raw_key = (api_key or os.getenv("AIOPS_API_KEY", "")).strip()
    Config.api_key      = raw_key or None
    Config.service_name = os.getenv("AIOPS_SERVICE_NAME", "unknown-service").strip() or "unknown-service"
    Config.environment  = os.getenv("AIOPS_ENV", "production").strip() or "production"
    # rstrip("/") prevents double-slash in constructed URLs like
    # "https://host//v1/sdk/exception" when the env var includes a trailing slash.
    Config.platform_url = os.getenv(
        "AIOPS_PLATFORM_URL", "https://aiops.1genimpact.cloud"
    ).rstrip("/")
    # Optional: the URL of this service's fixer endpoint.
    # Platform uses this to call back and apply automated fixes.
    Config.base_url = os.getenv("AIOPS_SERVICE_BASE_URL")

    if not Config.api_key:
        raise RuntimeError(
            "AIOps API key is required. "
            "Pass it to aiops_sdk.init(api_key='...') or set the AIOPS_API_KEY environment variable."
        )
