"""
FactRetriever
Generated by Eden via recursive self-improvement
2025-10-28 04:44:28.501160
"""

class FactRetriever:
    """
    A class that helps manage and retrieve facts/questions with associated information.
    
    Attributes:
        facts: List of facts, each represented as a dictionary with keys 'question', 
               'answer', 'tags', and 'source'.
    """

    def __init__(self):
        self.facts = []

    def add_fact(self, question, answer, tags=None, source=None):
        """
        Add a new fact/question to the knowledge base.
        
        Args:
            question (str): The question or topic of the fact.
            answer (str): The answer or explanation.
            tags (list of str, optional): List of relevant tags for this fact.
            source (str, optional): Source of the information.
        """
        if tags is None:
            tags = []
        if source is None:
            source = "Unknown"
            
        new_fact = {
            'question': question,
            'answer': answer,
            'tags': tags,
            'source': source
        }
        self.facts.append(new_fact)

    def search(self, query, exact_match=False, limit=None, case_sensitive=True):
        """
        Search for facts based on a query string. Can match against the question or tags.
        
        Args:
            query (str): The search term to look for.
            exact_match (bool, optional): If True, searches only for exact matches of the query in questions.
            limit (int, optional): Maximum number of results to return.
            case_sensitive (bool, optional): Whether the search is case-sensitive or not.
            
        Returns:
            list of dictionaries: Facts that match the query, with their details.
        """
        results = []
        for fact in self.facts:
            if self._matches_query(fact, query, exact_match, case_sensitive):
                results.append({
                    'question': fact['question'],
                    'answer': fact['answer'],
                    'tags': fact['tags'],
                    'source': fact['source']
                })
            if limit and len(results) >= limit:
                break
        return results

    def _matches_query(self, fact, query, exact_match, case_sensitive):
        """
        Helper method to check if a fact matches the given query.
        
        Args:
            fact (dict): The fact to check.
            query (str): The search term.
            exact_match (bool): Whether to require an exact match in questions.
            case_sensitive (bool): Case sensitivity of the search.
            
        Returns:
            bool: True if the fact matches, False otherwise.
        """
        question = fact['question']
        tags = ' '.join(fact['tags'])
        
        query_lower = query.lower() if not case_sensitive else query
        question_lower = question.lower() if not case_sensitive else question
        
        if exact_match:
            match_question = (question == query) if case_sensitive else (question_lower == query_lower)
            if match_question:
                return True
                
        # Search across question or tags
        combined_text = f"{question} {' '.join(fact['tags'])}"
        return query.lower() in combined_text.lower()

# Example usage:
if __name__ == "__main__":
    retriever = FactRetriever()
    
    # Add some facts
    retriever.add_fact(
        question="What is Python?",
        answer="A high-level programming language.",
        tags=["programming", "language"],
        source="Wikipedia"
    )
    
    retriever.add_fact(
        question="Who created Python?",
        answer="Guido van Rossum",
        tags=["history", "creator"],
        source="Python.org"
    )
    
    # Search examples
    print("Search for 'Python':")
    results = retriever.search(query="Python")
    for res in results:
        print(f"- {res['question']}")
        
    print("\nExact match search:")
    exact_results = retriever.search(query="What is Python?", exact_match=True)
    if exact_results:
        print(exact_results[0]['answer'])
    else:
        print("No exact matches found.")