from google import genai
from .memory import Memory
from .exceptions import InvalidAPIKeyException, ChatException


class Dracula:
    def __init__(
        self,
        api_key: str,
        model: str = "gemini-3-flash-preview",
        max_messages: int = 10,
    ):
        if not api_key:
            raise InvalidAPIKeyException("API Key cannot be empty.")

        try:
            self.client = genai.Client(api_key=api_key)
            self.model_name = model

        except Exception:
            raise InvalidAPIKeyException("Invalid API key or model name.")

        self.memory = Memory(max_messages=max_messages)

    def chat(self, message: str) -> str:
        if not message:
            raise ChatException("Message cannot be empty.")

        try:
            self.memory.add_message("user", message)

            history = [
                genai.types.Content(
                    role=msg["role"], parts=[genai.types.Part(text=msg["content"])]
                )
                for msg in self.memory.get_history()
            ]

            response = self.client.models.generate_content(
                model=self.model_name, contents=history
            )

            reply = response.text

            self.memory.add_message("model", reply)
            return reply

        except Exception as e:
            raise ChatException(f"Something went wrong: {str(e)}")

    def clear_memory(self):
        self.memory.clear()

    def get_history(self):
        return self.memory.get_history()
