"""
Semantic Processor - True understanding beyond pattern matching
"""
from collections import defaultdict

class SemanticProcessor:
    def __init__(self):
        self.concept_graph = defaultdict(lambda: {"related": [], "properties": [], "examples": []})
        self.load_concepts()
    
    def load_concepts(self):
        """Initialize basic concept knowledge"""
        # Core concepts
        self.add_concept("dog", {
            "related": ["animal", "pet", "mammal"],
            "properties": ["has_legs:4", "can_bark", "domesticated"],
            "examples": ["labrador", "poodle", "german_shepherd"]
        })
        
        self.add_concept("animal", {
            "related": ["organism", "living_thing"],
            "properties": ["can_move", "needs_food", "breathes"],
            "examples": ["dog", "cat", "bird", "fish"]
        })
        
        self.add_concept("learning", {
            "related": ["knowledge", "education", "improvement"],
            "properties": ["requires_practice", "builds_skill", "needs_feedback"],
            "examples": ["studying", "training", "practicing"]
        })
    
    def add_concept(self, concept_name, data):
        """Add a concept to the semantic network"""
        self.concept_graph[concept_name].update(data)
    
    def understand_concept(self, concept):
        """Semantic understanding of a concept"""
        if concept not in self.concept_graph:
            return {
                "understood": False,
                "reason": "Concept not in knowledge base",
                "suggestion": "Learn more about this concept"
            }
        
        concept_data = self.concept_graph[concept]
        
        return {
            "understood": True,
            "concept": concept,
            "related_concepts": concept_data["related"],
            "properties": concept_data["properties"],
            "examples": concept_data["examples"],
            "semantic_depth": len(concept_data["related"]) + len(concept_data["properties"])
        }
    
    def find_relationship(self, concept1, concept2):
        """Find semantic relationship between concepts"""
        if concept1 not in self.concept_graph or concept2 not in self.concept_graph:
            return {"relationship": "unknown", "path": []}
        
        # Direct relationship
        if concept2 in self.concept_graph[concept1]["related"]:
            return {"relationship": "directly_related", "path": [concept1, concept2]}
        
        # Check through one hop
        for related in self.concept_graph[concept1]["related"]:
            if concept2 in self.concept_graph[related]["related"]:
                return {"relationship": "indirectly_related", "path": [concept1, related, concept2]}
        
        return {"relationship": "no_clear_path", "path": []}
    
    def interpret_meaning(self, text):
        """Interpret semantic meaning of text"""
        words = text.lower().split()
        
        understood_concepts = []
        unknown_concepts = []
        
        for word in words:
            if word in self.concept_graph:
                understood_concepts.append(word)
            else:
                # Try to find partial matches
                partial = [c for c in self.concept_graph if c in word or word in c]
                if partial:
                    understood_concepts.extend(partial)
                else:
                    unknown_concepts.append(word)
        
        return {
            "text": text,
            "understood": understood_concepts,
            "unknown": unknown_concepts,
            "understanding_rate": len(understood_concepts) / len(words) if words else 0
        }
    
    def explain_concept(self, concept):
        """Generate natural explanation of concept"""
        understanding = self.understand_concept(concept)
        
        if not understanding["understood"]:
            return f"I don't have deep knowledge of '{concept}' yet."
        
        explanation = f"{concept.capitalize()} is"
        
        if understanding["related_concepts"]:
            explanation += f" related to {', '.join(understanding['related_concepts'][:3])}"
        
        if understanding["properties"]:
            props = [p.replace("_", " ") for p in understanding["properties"][:2]]
            explanation += f" and has properties like {', '.join(props)}"
        
        if understanding["examples"]:
            explanation += f". Examples include {', '.join(understanding['examples'][:3])}"
        
        return explanation + "."

if __name__ == "__main__":
    print("SEMANTIC PROCESSOR TEST")
    
    processor = SemanticProcessor()
    
    # Test concept understanding
    print("\n🧠 Understanding 'dog':")
    result = processor.understand_concept("dog")
    print(f"   Related: {result['related_concepts']}")
    print(f"   Properties: {result['properties']}")
    
    # Test relationship finding
    print("\n🔗 Relationship between 'dog' and 'animal':")
    result = processor.find_relationship("dog", "animal")
    print(f"   Type: {result['relationship']}")
    print(f"   Path: {' → '.join(result['path'])}")
    
    # Test meaning interpretation
    print("\n📝 Interpreting: 'dogs are learning animals':")
    result = processor.interpret_meaning("dogs are learning animals")
    print(f"   Understood: {result['understood']}")
    print(f"   Understanding: {result['understanding_rate']:.0%}")
    
    # Test explanation
    print("\n💬 Explain 'learning':")
    explanation = processor.explain_concept("learning")
    print(f"   {explanation}")
    
    print(f"\n📊 Concepts in semantic network: {len(processor.concept_graph)}")
    
    print("\n🧠 Eden can now:")
    print("   - Understand concepts semantically")
    print("   - Find relationships between ideas")
    print("   - Interpret meaning beyond patterns")
    print("   - Explain concepts naturally")
    
    print("\n✅ SEMANTIC PROCESSOR OPERATIONAL")
