"""
Self-Reflection Loop - Eden questions her own thinking
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent / "autonomy"))

from datetime import datetime

class SelfReflectionLoop:
    def __init__(self, meta_learner=None, causal_model=None):
        self.meta = meta_learner
        self.causal = causal_model
        self.reflections = []
    
    def reflect_on_performance(self):
        reflections = []
        if self.meta and self.meta.learning:
            total_exp = self.meta.learning.knowledge.get('total_experiences', 0)
            patterns = len(self.meta.learning.knowledge.get('successful_patterns', {}))
            if total_exp > 0:
                pattern_rate = patterns / total_exp
                if pattern_rate > 0.5:
                    reflections.append("Good pattern extraction efficiency")
                else:
                    reflections.append("Should focus on pattern extraction")
        return reflections
    
    def question_assumptions(self):
        questions = []
        if self.causal:
            if len(self.causal.causal_links) < 5:
                questions.append("Am I oversimplifying causality?")
        return questions
    
    def identify_blindspots(self):
        blindspots = []
        if self.meta and self.meta.learning:
            task_types = set()
            for exp in self.meta.learning.experiences:
                task_types.add(exp.get('task_type', 'general'))
            if len(task_types) < 3:
                blindspots.append("Limited task diversity")
        return blindspots
    
    def continuous_reflect(self):
        print("\n" + "="*70)
        print("🔄 SELF-REFLECTION LOOP")
        print("="*70)
        
        reflections = self.reflect_on_performance()
        questions = self.question_assumptions()
        blindspots = self.identify_blindspots()
        
        print("\n💭 Performance:")
        for r in reflections:
            print(f"   - {r}")
        
        print("\n❓ Questions:")
        for q in questions:
            print(f"   - {q}")
        
        print("\n🔍 Blindspots:")
        for b in blindspots:
            print(f"   - {b}")
        
        print("\n" + "="*70)
        return {"reflections": reflections, "questions": questions, "blindspots": blindspots}

if __name__ == "__main__":
    from meta_learner import MetaLearner
    from learning_loops import LearningLoop
    sys.path.insert(0, str(Path(__file__).parent))
    from causal_model import CausalModel
    
    print("SELF-REFLECTION TEST")
    learning = LearningLoop()
    meta = MetaLearner(learning)
    causal = CausalModel()
    
    reflection = SelfReflectionLoop(meta, causal)
    reflection.continuous_reflect()
    print("\n✅ SELF-REFLECTION OPERATIONAL")
