from contextvars import ContextVar
from types import SimpleNamespace

from hvac import Client
from pydantic import Field
from langfuse import Langfuse
from langfuse.decorators import langfuse_context
from pydantic_settings import BaseSettings

buffer: ContextVar[str] = ContextVar("buffer", default="")
tool_buffer: ContextVar[str] = ContextVar("tool_buffer", default="")
tool_id: ContextVar[str | None] = ContextVar("tool_id", default=None)
tool_name: ContextVar[str | None] = ContextVar("tool_name", default=None)

context = SimpleNamespace(
    buffer=buffer,
    tool_buffer=tool_buffer,
    tool_id=tool_id,
    tool_name=tool_name,
)

client = Client(url="https://vault.ia-innovacion.work")

if not client.is_authenticated():
    raise Exception("Vault authentication failed")

secret_map = client.secrets.kv.v2.read_secret_version(
    path="banortegpt", mount_point="secret"
)["data"]["data"]


class Settings(BaseSettings):
    model: str = "gpt-4o"
    model_temperature: int = 0
    embedding_model: str = "text-embedding-3-large"
    message_limit: int = 10
    storage_bucket: str = "riesgosreferences2"
    vector_index: str = "MayaRiesgos2"
    search_limit: int = 5
    host: str = "0.0.0.0"
    port: int = 8000

    azure_endpoint: str = Field(default_factory=lambda: secret_map["azure_endpoint"])
    openai_api_key: str = Field(default_factory=lambda: secret_map["openai_api_key"])
    openai_api_version: str = Field(
        default_factory=lambda: secret_map["openai_api_version"]
    )
    azure_blob_connection_string: str = Field(
        default_factory=lambda: secret_map["azure_blob_connection_string"]
    )
    qdrant_url: str = Field(default_factory=lambda: secret_map["qdrant_api_url"])
    qdrant_api_key: str | None = Field(
        default_factory=lambda: secret_map["qdrant_api_key"]
    )
    mongodb_url: str = Field(
        default_factory=lambda: secret_map["cosmosdb_connection_string"]
    )
    langfuse_host: str | None = None
    langfuse_public_key: str | None = None
    langfuse_secret_key: str | None = None

    async def init_mongo_db(self):
        from banortegpt.database.mongo_memory.models import Conversation
        from beanie import init_beanie
        from motor.motor_asyncio import AsyncIOMotorClient

        client = AsyncIOMotorClient(self.mongodb_url)

        await init_beanie(
            database=client.banortegptdos,
            document_models=[Conversation],
        )

    def init_langfuse(self):
        langfuse_context.configure(
            host=self.langfuse_host,
            public_key=self.langfuse_public_key,
            secret_key=self.langfuse_secret_key,
        )

    def get_langfuse(self):
        return Langfuse(
            host=self.langfuse_host,
            public_key=self.langfuse_public_key,
            secret_key=self.langfuse_secret_key,
        )


config = Settings()
