import json

from analogai.deepthink.infrastructure.gateways.llm.gateway import LlmGateway


class FakeLlmGatewayImpl(LlmGateway):
    def __init__(self, model: str, max_tokens: int | None = None):
        self._model = model
        self._max_tokens = max_tokens
        self._system_prompt = ""

    def set_system_prompt(self, system_prompt: str) -> None:
        self._system_prompt = system_prompt

    def set_model(self, model_id: str) -> None:
        self._model = model_id

    def generate_completion(self, user_message: str) -> str:
        message = user_message.strip()
        if self._looks_like_sentence_transform_request(message):
            sentence_text = self._extract_sentence_text(message)
            parsed = {
                "intent_type": "making_statement",
                "subject": sentence_text,
                "predicate": {"relation": "is", "complement": "unknown"},
            }
            return json.dumps({"sentences": [parsed]})
        return "I don't know"

    async def generate_streaming_completion(self, user_message: str):
        yield self.generate_completion(user_message)

    @staticmethod
    def _looks_like_sentence_transform_request(message: str) -> bool:
        lowered = message.lower()
        return "sentence:" in lowered or "\"sentences\"" in lowered or "intent_type" in lowered

    @staticmethod
    def _extract_sentence_text(message: str) -> str:
        lines = [line.strip() for line in message.splitlines() if line.strip()]
        if not lines:
            return ""
        last_line = lines[-1]
        if last_line.lower().startswith("sentence:"):
            return last_line.split(":", 1)[1].strip()
        return last_line
