"""
Common Sense Knowledge Base - Basic understanding of the world
"""

class CommonSenseKB:
    def __init__(self):
        self.physics_rules = {}
        self.social_rules = {}
        self.practical_knowledge = {}
        self.load_knowledge()
    
    def load_knowledge(self):
        """Load basic common sense knowledge"""
        
        # Physics common sense
        self.physics_rules = {
            "gravity": "Objects fall down without support",
            "solid_objects": "Solid objects cannot pass through each other",
            "time": "Time only moves forward",
            "fire": "Fire is hot and can burn things",
            "water": "Water flows downward and makes things wet",
            "light": "Light travels in straight lines",
            "temperature": "Hot things cool down, cold things warm up"
        }
        
        # Social common sense
        self.social_rules = {
            "greeting": "People greet each other when meeting",
            "personal_space": "People prefer personal space",
            "turn_taking": "In conversation, people take turns speaking",
            "helping": "Helping others is generally positive",
            "honesty": "Being truthful is generally valued",
            "politeness": "Saying please and thank you is polite"
        }
        
        # Practical knowledge
        self.practical_knowledge = {
            "eating": "People need to eat regularly to survive",
            "sleeping": "People need sleep to function",
            "tools": "Tools help accomplish tasks more easily",
            "learning": "Practice improves skills over time",
            "planning": "Planning ahead helps achieve goals",
            "communication": "Clear communication prevents misunderstandings"
        }
    
    def check_statement(self, statement):
        """Check if statement aligns with common sense"""
        statement_lower = statement.lower()
        
        violations = []
        confirmations = []
        
        # Check physics
        if "fall up" in statement_lower:
            violations.append("Objects don't fall upward (violates gravity)")
        if "through wall" in statement_lower or "pass through" in statement_lower:
            violations.append("Solid objects can't pass through each other")
        
        # Check social
        if "never speak" in statement_lower and "conversation" in statement_lower:
            violations.append("Conversations require speaking")
        
        # Check practical
        if "never sleep" in statement_lower or "no sleep" in statement_lower:
            violations.append("Humans need sleep to survive")
        if "never eat" in statement_lower:
            violations.append("Humans need food to survive")
        
        # Check confirmations
        if "gravity" in statement_lower and "fall" in statement_lower:
            confirmations.append("Aligns with gravity rules")
        if "practice" in statement_lower and "improve" in statement_lower:
            confirmations.append("Aligns with learning principles")
        
        return {
            "statement": statement,
            "makes_sense": len(violations) == 0,
            "violations": violations,
            "confirmations": confirmations
        }
    
    def reason_about(self, scenario):
        """Apply common sense reasoning to scenario"""
        scenario_lower = scenario.lower()
        
        relevant_knowledge = []
        predictions = []
        
        # Physics reasoning
        if "drop" in scenario_lower or "fall" in scenario_lower:
            relevant_knowledge.append(self.physics_rules["gravity"])
            predictions.append("Object will fall downward")
        
        if "fire" in scenario_lower or "flame" in scenario_lower:
            relevant_knowledge.append(self.physics_rules["fire"])
            predictions.append("Will be hot, risk of burning")
        
        # Social reasoning
        if "meet" in scenario_lower or "greeting" in scenario_lower:
            relevant_knowledge.append(self.social_rules["greeting"])
            predictions.append("People will likely greet each other")
        
        if "conversation" in scenario_lower:
            relevant_knowledge.append(self.social_rules["turn_taking"])
            predictions.append("People will take turns speaking")
        
        # Practical reasoning
        if "practice" in scenario_lower or "learn" in scenario_lower:
            relevant_knowledge.append(self.practical_knowledge["learning"])
            predictions.append("Skill will improve with practice")
        
        return {
            "scenario": scenario,
            "relevant_knowledge": relevant_knowledge,
            "predictions": predictions,
            "confidence": len(relevant_knowledge) / 3  # 0-1 based on matches
        }
    
    def explain_why(self, question):
        """Explain why something is true using common sense"""
        question_lower = question.lower()
        
        explanations = []
        
        if "fall" in question_lower:
            explanations.append("Because of gravity - all objects are pulled toward Earth")
        
        if "sleep" in question_lower:
            explanations.append("Because bodies need rest to repair and restore energy")
        
        if "eat" in question_lower:
            explanations.append("Because bodies need fuel (food) to produce energy")
        
        if "practice" in question_lower and "improve" in question_lower:
            explanations.append("Because repetition strengthens neural pathways and builds muscle memory")
        
        if "hot" in question_lower:
            explanations.append("Because heat is energy that transfers to other objects")
        
        if not explanations:
            explanations.append("I need more context to explain this")
        
        return {
            "question": question,
            "explanations": explanations
        }

if __name__ == "__main__":
    print("COMMON SENSE KB TEST")
    
    kb = CommonSenseKB()
    
    # Test statement checking
    print("\n✅ Checking statement: 'Objects fall down due to gravity'")
    result = kb.check_statement("Objects fall down due to gravity")
    print(f"   Makes sense: {result['makes_sense']}")
    print(f"   Confirmations: {result['confirmations']}")
    
    print("\n❌ Checking statement: 'I can walk through walls'")
    result = kb.check_statement("I can walk through walls")
    print(f"   Makes sense: {result['makes_sense']}")
    if result['violations']:
        print(f"   Violations: {result['violations']}")
    
    # Test reasoning
    print("\n🤔 Reasoning about: 'If I drop a ball'")
    result = kb.reason_about("If I drop a ball")
    print(f"   Predictions: {result['predictions']}")
    print(f"   Confidence: {result['confidence']:.0%}")
    
    # Test explanations
    print("\n💡 Why do people need to sleep?")
    result = kb.explain_why("Why do people need to sleep?")
    print(f"   {result['explanations'][0]}")
    
    print(f"\n📚 Knowledge areas:")
    print(f"   Physics rules: {len(kb.physics_rules)}")
    print(f"   Social rules: {len(kb.social_rules)}")
    print(f"   Practical knowledge: {len(kb.practical_knowledge)}")
    
    print("\n🌍 Eden now has:")
    print("   - Basic physics understanding")
    print("   - Social reasoning")
    print("   - Practical knowledge")
    print("   - Common sense checking")
    
    print("\n✅ COMMON SENSE KB OPERATIONAL")
