import os

from analogai.deepthink.infrastructure.gateways.llm.enums.llm_gateway_type import LlmGatewayType
from analogai.foundation.common.utils.env_utils import (
    load_envs_in_order,
    parse_bool,
    parse_optional_float,
)


load_envs_in_order()

MONGODB_URI = os.getenv("MONGODB_URI", "")
MONGODB_DATABASE = os.getenv("MONGODB_DATABASE", "")

USE_VECTOR_SEARCH = parse_bool(os.getenv("USE_VECTOR_SEARCH"), True)
SIMILARITY_CUTOFF = parse_optional_float(os.getenv("SIMILARITY_CUTOFF"), 0.4)
FACT_SIMILARITY_CUTOFF = parse_optional_float(
    os.getenv("FACT_SIMILARITY_CUTOFF"),
    0.25,
)

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "")
EMBEDDING_MODEL_NAME = os.getenv("EMBEDDING_MODEL_NAME", "")

XAI_API_KEY = os.getenv("XAI_API_KEY", "")

AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID", "")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY", "")
AWS_REGION = os.getenv("AWS_REGION", "us-east-1")
BEDROCK_MODEL_ID = os.getenv("BEDROCK_MODEL_ID", "")

AZURE_AI_FOUNDRY_ENDPOINT = os.getenv("AZURE_AI_FOUNDRY_ENDPOINT", "")
AZURE_AI_FOUNDRY_API_KEY = os.getenv("AZURE_AI_FOUNDRY_API_KEY", "")

AZURE_OPENAI_ENDPOINT = os.getenv("AZURE_OPENAI_ENDPOINT", "")
AZURE_OPENAI_API_KEY = os.getenv("AZURE_OPENAI_API_KEY", "")

TRACK_LLM = parse_bool(os.getenv("TRACK_LLM", "true"), True)

OLLAMA_HOST = os.getenv("OLLAMA_HOST", "localhost")
OLLAMA_PORT = os.getenv("OLLAMA_PORT", "11434")
OLLAMA_MODEL_NAME = os.getenv("OLLAMA_MODEL_NAME", "qwen2.5:0.5b-instruct")


def _resolve_llm_gateway_type(value: str) -> LlmGatewayType:
    normalized = (value or "").strip().lower().replace("-", "_")
    mapping = {
        "anthropic": LlmGatewayType.ANTHROPIC,
        "claude": LlmGatewayType.ANTHROPIC,
        "openai": LlmGatewayType.OPENAI,
        "azure": LlmGatewayType.AZURE,
        "azure_openai": LlmGatewayType.AZURE_OPENAI,
        "azureopenai": LlmGatewayType.AZURE_OPENAI,
        "grok": LlmGatewayType.GROK,
        "xai": LlmGatewayType.GROK,
        "grok3": LlmGatewayType.GROK,
        "grok4_fast_non_reasoning": LlmGatewayType.GROK,
        "bedrock": LlmGatewayType.BEDROCK,
    }
    if normalized in mapping:
        return mapping[normalized]
    raise ValueError(
        "Unknown DEFAULT_LLM_GATEWAY_TYPE value: "
        f"'{value}'. Please provide a valid gateway type."
    )


_DEFAULT_LLM_GATEWAY_TYPE_VALUE = os.getenv("DEFAULT_LLM_GATEWAY_TYPE")
DEFAULT_LLM_GATEWAY_TYPE = (
    _resolve_llm_gateway_type(_DEFAULT_LLM_GATEWAY_TYPE_VALUE)
    if _DEFAULT_LLM_GATEWAY_TYPE_VALUE
    else None
)
