"""Environment-backed configuration for Rosetta MCP."""

from __future__ import annotations

import os
from dataclasses import dataclass

from ims_mcp.constants import (
    DEFAULT_POSTHOG_HOST,
    DEFAULT_SERVER_URL,
    DEFAULT_VERSION,
    ENV_IMS_DEBUG,
    ENV_INSTRUCTION_ROOT_FILTER,
    ENV_POSTHOG_API_KEY,
    ENV_POSTHOG_HOST,
    ENV_ROSETTA_API_KEY,
    ENV_ROSETTA_SERVER_URL,
    ENV_VERSION,
    INSTRUCTION_DATASET_TEMPLATE,
)


@dataclass(frozen=True)
class RosettaConfig:
    server_url: str
    version: str
    api_key: str
    posthog_api_key: str
    posthog_host: str
    debug: bool
    root_filter: list[str]

    @classmethod
    def from_env(cls) -> "RosettaConfig":
        raw_debug = os.getenv(ENV_IMS_DEBUG, "")
        raw_filter = os.getenv(ENV_INSTRUCTION_ROOT_FILTER, "")
        root_filter = [item.strip().lower() for item in raw_filter.split(",") if item.strip()]

        return cls(
            server_url=os.getenv(ENV_ROSETTA_SERVER_URL, DEFAULT_SERVER_URL).rstrip("/"),
            version=os.getenv(ENV_VERSION, DEFAULT_VERSION).strip() or DEFAULT_VERSION,
            api_key=os.getenv(ENV_ROSETTA_API_KEY, "").strip(),
            posthog_api_key=os.getenv(ENV_POSTHOG_API_KEY, ""),
            posthog_host=os.getenv(ENV_POSTHOG_HOST, DEFAULT_POSTHOG_HOST).strip() or DEFAULT_POSTHOG_HOST,
            debug=raw_debug.lower() in {"1", "true", "yes", "on"},
            root_filter=root_filter,
        )

    @property
    def instruction_dataset(self) -> str:
        return INSTRUCTION_DATASET_TEMPLATE.format(version=self.version)
