from __future__ import annotations

from typing import Optional

from analogai.foundation.infrastructure.services.embedding_service import EmbeddingService  # type: ignore[import-not-found]
from analogai.foundation.settings import config as infra_config
from analogai.deepthink.settings import config as app_config
from analogai.deepthink.messaging.fact.repositories.fact_repository import FactRepositoryPort
from analogai.deepthink.messaging.fact.repositories.infrastructure.fact_repository import (
    InMemoryFactRepository,
    MongoFactRepository,
)
from analogai.deepthink.messaging.fact.services.fact_service import (
    FactServicePort,
    InMemoryFactService,
    RepositoryBackedFactService,
)
from analogai.deepthink.messaging.fact.enums.fact_embedding_mode import FactEmbeddingMode


class FactServiceFactory:
    def __init__(
        self,
        embedding_service: Optional[EmbeddingService] = None,
        repository: Optional[FactRepositoryPort] = None,
    ):
        self._embedding_service = embedding_service
        self._repository = repository

    def create(self) -> FactServicePort:
        use_vector_search = bool(
            infra_config.get(
                "USE_VECTOR_SEARCH",
                infra_config.get("vector.enabled", True),
            )
        )
        embedding_mode = (
            FactEmbeddingMode.ENABLED
            if use_vector_search
            else FactEmbeddingMode.DISABLED
        )
        if self._repository is None:
            environment = app_config.get("ENVIRONMENT", "development")
            if environment in {"production", "testing"}:
                self._repository = MongoFactRepository()
            else:
                self._repository = InMemoryFactRepository()
        if self._repository is not None:
            return RepositoryBackedFactService(
                self._repository,
                embedding_service=self._embedding_service,
                embedding_mode=embedding_mode,
            )
        return InMemoryFactService(
            embedding_service=self._embedding_service,
            embedding_mode=embedding_mode,
        )
