import logging

import ollama
from ollama._types import ResponseError

logger = logging.getLogger(__name__)


class FactChecker:
    """Handles fact checking of text."""

    def __init__(self, model_name: str = "deepseek-coder"):
        """Initialize the fact checker.

        Args:
            model_name: Name of the Ollama model to use
        """
        self.model_name = model_name

    def _safe_generate(self, prompt: str) -> str:
        """Safely generate response from Ollama."""
        try:
            # Add system context for deepseek-coder
            system_prompt = "You are a fact-checking assistant. Respond with 'yes' or 'no' only."
            response = ollama.generate(model=self.model_name, prompt=prompt, system=system_prompt)
            # Extract response content from the dictionary
            return response.get("response", "")
        except ResponseError as e:
            logger.error(f"Ollama error: {e}")
            return ""
        except Exception as e:
            logger.error(f"Unexpected error calling Ollama: {e}")
            return ""

    def validate_question(self, question: str, context: str) -> bool:
        """Validate if the question is relevant to the context.

        Args:
            question: The generated question
            context: The context from which the question was generated

        Returns:
            bool: True if the question is valid, False otherwise
        """
        question_text = str(question).lower()
        context_text = str(context).lower()
        prompt = f"Is the following question relevant to the context? Question: {question_text} Context: {context_text}"
        response = self._safe_generate(prompt)

        # Check if the response indicates validity
        return "yes" in response.lower()

    def fact_check(self, question: str, answer: str, context: str) -> bool:
        """Check if the answer to the question is factually correct.

        Args:
            question: The generated question
            answer: The generated answer
            context: The context from which the question and answer were generated

        Returns:
            bool: True if the answer is factually correct, False otherwise
        """
        question_text = str(question).lower()
        answer_text = str(answer).lower()
        context_text = str(context).lower()
        prompt = f"Is the following answer correct? Question: {question_text} Answer: {answer_text} Context: {context_text}"
        response = self._safe_generate(prompt)

        # Check if the response indicates correctness
        return "yes" in response.lower()
