from __future__ import annotations

import time

from analogai.deepthink.infrastructure.gateways.llm.gateway import LlmGateway
from analogai.foundation.common.logging.app_logger import app_logger


class QuestionAnsweringLlmClient:
    def __init__(self, gateway: LlmGateway):
        self._gateway = gateway

    def generate_answer(self, user_message: str, system_prompt: str | None = None) -> str | None:
        if system_prompt is not None:
            try:
                self._gateway.set_system_prompt(system_prompt)
            except AttributeError:
                pass
        total_chars, estimated_tokens = _estimate_prompt_usage(user_message, system_prompt)
        app_logger.debug(
            "[QuestionAnsweringLlmClient] prompt_usage chars=%d est_tokens=%d",
            total_chars,
            estimated_tokens,
        )
        started_at = time.perf_counter()
        response = self._gateway.generate_completion(user_message)
        app_logger.debug(
            "[QuestionAnsweringLlmClient] generate_completion duration=%.2fs",
            time.perf_counter() - started_at,
        )
        if response and str(response).strip():
            return response
        retry_started_at = time.perf_counter()
        retry = self._gateway.generate_completion(user_message)
        app_logger.debug(
            "[QuestionAnsweringLlmClient] retry duration=%.2fs",
            time.perf_counter() - retry_started_at,
        )
        if retry and str(retry).strip():
            return retry
        return None


def _estimate_prompt_usage(user_message: str, system_prompt: str | None) -> tuple[int, int]:
    system_text = system_prompt or ""
    user_text = user_message or ""
    total_chars = len(system_text) + len(user_text)
    estimated_tokens = max(1, total_chars // 4) if total_chars else 0
    return total_chars, estimated_tokens
