from __future__ import annotations

from pathlib import Path
from datetime import datetime
from typing import Optional

from analogai.deepthink.infrastructure.gateways.llm.gateway import LlmGateway
from analogai.deepthink.infrastructure.gateways.llm.llm_gateway_provider_factory import LlmGatewayProviderFactory
from analogai.foundation.settings import config
from analogai.foundation.common.logging.app_logger import app_logger


class ChatResponseSynthesizer:
    def __init__(self, llm_gateway: Optional[LlmGateway] = None):
        self._llm_gateway = llm_gateway

    def synthesize(self, chat_statements: str) -> str:
        text = (chat_statements or "").strip()
        if not text:
            return ""
        if not self._is_enabled():
            return text
        current_time = datetime.now().isoformat(timespec="seconds")
        prompt = _load_prompt().format(chat_statements=text, current_time=current_time)
        gateway = self._llm_gateway or LlmGatewayProviderFactory.create_gateway(
            system_prompt="",
            max_tokens=200,
        )
        try:
            app_logger.debug(
                "[ChatSynthesizer] Prompt built with current_time=%s", current_time
            )
            response = gateway.generate_completion(prompt)
        except Exception:
            return text
        return response.strip() or text

    def _is_enabled(self) -> bool:
        value = config.get("chat.synthesizer.enabled", True)
        return bool(value)


def _load_prompt() -> str:
    prompts_dir = Path(__file__).resolve().parents[2] / "infrastructure" / "prompts"
    prompt_path = prompts_dir / "chat_synthesizer_prompt.txt"
    if not prompt_path.exists():
        raise FileNotFoundError(f"Prompt file not found: {prompt_path}")
    return prompt_path.read_text(encoding="utf-8")
