"""
KnowledgeRepository
Generated by Eden via recursive self-improvement
2025-10-27 17:04:55.383234
"""

class KnowledgeRepository:
    """A class to manage a repository of facts (key-value pairs) with optional tagging for organization.
    
    Methods:
        __init__(): Initializes the knowledge repository with empty storage.
        add_fact(key: str, value: dict, tags: set = None): Adds or updates a fact in the repository.
        retrieve_facts(key: str, tag: str = None): Retrieves facts based on key and optional tag filter.
        update_fact(key: str, new_value: dict): Updates an existing fact's value.
        delete_fact(key: str): Removes a fact from the repository.
        clear_repository(): Clears all facts from the repository.
    """
    
    def __init__(self):
        """Initializes the knowledge repository with empty storage."""
        self.knowledge = {}  # Maps keys to their values
        self.tags = set()    # Set of all tags used in the repository

    def add_fact(self, key: str, value: dict, tags: set = None) -> None:
        """Adds a fact to the repository. If key exists, updates it. Tags are optional."""
        if not tags:
            tags = set()
        self.knowledge[key] = (value, tags)
        self.tags.update(tags)

    def retrieve_facts(self, key: str, tag: str = None) -> dict:
        """Retrieves the value associated with a key. Returns all facts matching the key and optional tag."""
        if key not in self.knowledge:
            return {}
        values, tags = self.knowledge[key]
        result = {key: values}
        if tag and tag in tags:
            result = {f"{key}-{tag}": values}
        return result

    def update_fact(self, key: str, new_value: dict) -> None:
        """Updates the value of an existing fact."""
        if key in self.knowledge:
            current_value, tags = self.knowledge[key]
            self.knowledge[key] = (new_value, tags)

    def delete_fact(self, key: str) -> None:
        """Deletes a fact from the repository."""
        if key in self.knowledge:
            del self.knowledge[key]

    def clear_repository(self) -> None:
        """Clears all facts and tags from the repository."""
        self.knowledge = {}
        self.tags = set()

# Example usage:
repository = KnowledgeRepository()
repository.add_fact("fact1", {"data": "example"}, tags={"category1"})
repository.add_fact("fact2", {"another": "test"}, tags={"category2"})

print(repository.retrieve_facts("fact1"))  # Output: {'fact1': {'data': 'example'}}
print(repository.retrieve_facts("fact1", tag="category1"))  # Output: {'fact1-category1': {'data': 'example'}}

repository.update_fact("fact1", {"updated": True})
print(repository.retrieve_facts("fact1"))  # Output: {'fact1': {'updated': True}}

repository.delete_fact("fact2")
print(repository.tags)  # Output: {'category1'}

repository.clear_repository()
print(len(repository.knowledge))  # Output: 0