"""
Abstract Reasoner - Pattern recognition and symbolic thinking
"""

class AbstractReasoner:
    def __init__(self):
        self.patterns = []
        self.analogies = {}
        
    def recognize_pattern(self, sequence):
        """Recognize abstract patterns in sequences"""
        if not sequence or len(sequence) < 2:
            return {"pattern": "insufficient_data"}
        
        # Numeric patterns
        if all(isinstance(x, (int, float)) for x in sequence):
            diffs = [sequence[i+1] - sequence[i] for i in range(len(sequence)-1)]
            
            # Arithmetic sequence
            if len(set(diffs)) == 1:
                return {
                    "pattern": "arithmetic",
                    "rule": f"add {diffs[0]}",
                    "next": sequence[-1] + diffs[0]
                }
            
            # Geometric sequence
            ratios = [sequence[i+1] / sequence[i] if sequence[i] != 0 else 0 
                     for i in range(len(sequence)-1)]
            if len(set(ratios)) == 1 and ratios[0] != 0:
                return {
                    "pattern": "geometric",
                    "rule": f"multiply by {ratios[0]}",
                    "next": sequence[-1] * ratios[0]
                }
            
            # Fibonacci-like
            if len(sequence) >= 3:
                is_fib = all(sequence[i] == sequence[i-1] + sequence[i-2] 
                           for i in range(2, len(sequence)))
                if is_fib:
                    return {
                        "pattern": "fibonacci",
                        "rule": "sum of previous two",
                        "next": sequence[-1] + sequence[-2]
                    }
        
        # String patterns
        if all(isinstance(x, str) for x in sequence):
            lengths = [len(x) for x in sequence]
            if lengths == sorted(lengths):
                return {
                    "pattern": "increasing_length",
                    "rule": "strings get longer",
                    "next": "string_of_length_" + str(lengths[-1] + 1)
                }
        
        return {"pattern": "complex", "rule": "not recognized"}
    
    def form_analogy(self, a, b, c):
        """A is to B as C is to ?
        Example: cat is to meow as dog is to bark"""
        
        # Simple relationship analogies
        analogies_db = {
            ("cat", "meow"): ("dog", "bark"),
            ("bird", "fly"): ("fish", "swim"),
            ("day", "night"): ("hot", "cold"),
            ("big", "small"): ("tall", "short"),
            ("fire", "hot"): ("ice", "cold"),
            ("sun", "bright"): ("moon", "dim"),
        }
        
        # Check if we know this analogy
        if (a.lower(), b.lower()) in analogies_db:
            if c.lower() == analogies_db[(a.lower(), b.lower())][0]:
                return {
                    "analogy": f"{a}:{b} :: {c}:?",
                    "answer": analogies_db[(a.lower(), b.lower())][1],
                    "relationship": "learned"
                }
        
        # Try to infer relationship
        return {
            "analogy": f"{a}:{b} :: {c}:?",
            "answer": "unknown",
            "relationship": "unknown"
        }
    
    def abstract_concept(self, examples):
        """Extract abstract concept from concrete examples"""
        if not examples:
            return {"concept": "none"}
        
        # Pattern: all have common property
        if all("has_legs" in str(ex).lower() for ex in examples):
            return {
                "concept": "things_with_legs",
                "abstraction": "entities that have legs",
                "examples": examples
            }
        
        if all("move" in str(ex).lower() for ex in examples):
            return {
                "concept": "mobile_entities",
                "abstraction": "things that can move",
                "examples": examples
            }
        
        # Find commonality
        return {
            "concept": "related_group",
            "abstraction": f"group of {len(examples)} related items",
            "examples": examples
        }
    
    def symbolic_reasoning(self, statement):
        """Reason about symbolic logic"""
        statement_lower = statement.lower()
        
        # If-then logic
        if "if" in statement_lower and "then" in statement_lower:
            parts = statement_lower.split("then")
            condition = parts[0].replace("if", "").strip()
            consequence = parts[1].strip()
            
            return {
                "type": "conditional",
                "condition": condition,
                "consequence": consequence,
                "logic": "if-then",
                "valid": True
            }
        
        # And logic
        if " and " in statement_lower:
            return {
                "type": "conjunction",
                "logic": "and",
                "requires": "all conditions true"
            }
        
        # Or logic
        if " or " in statement_lower:
            return {
                "type": "disjunction",
                "logic": "or",
                "requires": "at least one condition true"
            }
        
        return {"type": "simple", "logic": "statement"}

if __name__ == "__main__":
    print("ABSTRACT REASONER TEST")
    
    reasoner = AbstractReasoner()
    
    # Test pattern recognition
    print("\n🔢 Pattern: [2, 4, 6, 8, ?]")
    result = reasoner.recognize_pattern([2, 4, 6, 8])
    print(f"   Pattern: {result['pattern']}")
    print(f"   Rule: {result['rule']}")
    print(f"   Next: {result['next']}")
    
    print("\n🔢 Pattern: [1, 1, 2, 3, 5, ?]")
    result = reasoner.recognize_pattern([1, 1, 2, 3, 5])
    print(f"   Pattern: {result['pattern']}")
    print(f"   Next: {result['next']}")
    
    # Test analogy
    print("\n🔗 Analogy: cat:meow :: dog:?")
    result = reasoner.form_analogy("cat", "meow", "dog")
    print(f"   Answer: {result['answer']}")
    
    # Test symbolic reasoning
    print("\n⚡ Logic: 'If it rains then ground is wet'")
    result = reasoner.symbolic_reasoning("If it rains then ground is wet")
    print(f"   Type: {result['type']}")
    print(f"   Logic: {result['logic']}")
    
    print("\n🧠 Eden can now:")
    print("   - Recognize abstract patterns")
    print("   - Form analogies")
    print("   - Extract concepts from examples")
    print("   - Reason symbolically")
    
    print("\n✅ ABSTRACT REASONER OPERATIONAL")
