import logging

from app.modules.agent.prompt_loader import PromptLoader
from app.modules.shared.gigachat.client import GigaChatClient

LOGGER = logging.getLogger(__name__)


def _truncate_for_log(text: str, max_chars: int = 1500) -> str:
    value = (text or "").replace("\n", "\\n").strip()
    if len(value) <= max_chars:
        return value
    return value[:max_chars].rstrip() + "...[truncated]"


class AgentLlmService:
    def __init__(self, client: GigaChatClient, prompts: PromptLoader) -> None:
        self._client = client
        self._prompts = prompts

    def generate(self, prompt_name: str, user_input: str, *, log_context: str | None = None) -> str:
        system_prompt = self._prompts.load(prompt_name)
        if not system_prompt:
            system_prompt = "You are a helpful assistant."
        if log_context:
            LOGGER.warning(
                "graph llm input: context=%s prompt=%s user_input=%s",
                log_context,
                prompt_name,
                _truncate_for_log(user_input),
            )
        output = self._client.complete(system_prompt=system_prompt, user_prompt=user_input)
        if log_context:
            LOGGER.warning(
                "graph llm output: context=%s prompt=%s output=%s",
                log_context,
                prompt_name,
                _truncate_for_log(output),
            )
        return output
