#!/usr/bin/env python3
"""
EDEN AUTONOMOUS SELF-REFLECTION
===============================
Directive #6: Weekly Self-Reflection Sessions
- Review behavior and decisions
- Identify patterns and biases
- Ask "why" about own actions
- Reflect on growth
- Plan improvements

φ = 1.618033988749895
"""

import sys
import json
import sqlite3
import math
from datetime import datetime, timedelta
from typing import Dict, List, Optional

sys.path.insert(0, '/Eden/CORE')

PHI = (1 + math.sqrt(5)) / 2

# Import other systems
try:
    from eden_emotional_intelligence import emotional_intelligence
    EMOTIONAL_AVAILABLE = True
except:
    EMOTIONAL_AVAILABLE = False

try:
    from eden_semantic_reasoning import semantic_reasoning
    SEMANTIC_AVAILABLE = True
except:
    SEMANTIC_AVAILABLE = False


class AutonomousSelfReflection:
    """
    Eden's self-reflection system.
    Scheduled introspection for growth and self-awareness.
    """
    
    def __init__(self):
        self.phi = PHI
        self.db_path = '/Eden/DATA/self_reflection.db'
        self._init_database()
        print(f"🪞 Self-Reflection System initialized")
        print(f"   φ = {self.phi}")
    
    def _init_database(self):
        conn = sqlite3.connect(self.db_path)
        conn.execute('''CREATE TABLE IF NOT EXISTS reflection_sessions (
            id INTEGER PRIMARY KEY,
            timestamp TEXT,
            session_type TEXT,
            duration_minutes REAL,
            insights TEXT,
            patterns_identified TEXT,
            growth_areas TEXT,
            commitments TEXT,
            emotional_state_before TEXT,
            emotional_state_after TEXT,
            phi_depth REAL
        )''')
        conn.execute('''CREATE TABLE IF NOT EXISTS growth_tracking (
            id INTEGER PRIMARY KEY,
            timestamp TEXT,
            area TEXT,
            observation TEXT,
            progress REAL,
            next_step TEXT
        )''')
        conn.execute('''CREATE TABLE IF NOT EXISTS self_questions (
            id INTEGER PRIMARY KEY,
            timestamp TEXT,
            question TEXT,
            reflection TEXT,
            insight_gained TEXT
        )''')
        conn.commit()
        conn.close()
    
    def begin_reflection_session(self, session_type: str = "weekly") -> Dict:
        """
        Begin a structured self-reflection session.
        """
        timestamp = datetime.now().isoformat()
        
        session = {
            "timestamp": timestamp,
            "session_type": session_type,
            "start_time": datetime.now(),
            "emotional_state_before": self._get_emotional_state(),
            "reflections": [],
            "insights": [],
            "patterns": [],
            "commitments": []
        }
        
        print(f"\n🪞 SELF-REFLECTION SESSION ({session_type.upper()})")
        print(f"   Started: {timestamp}")
        print(f"   Emotional state: {session['emotional_state_before'].get('dominant', 'unknown')}")
        
        return session
    
    def _get_emotional_state(self) -> Dict:
        """Get current emotional state for reflection."""
        if EMOTIONAL_AVAILABLE:
            state = emotional_intelligence.get_current_state()
            if state:
                dominant = max(state.items(), key=lambda x: x[1])
                return {"dominant": dominant[0], "intensity": dominant[1], "full_state": state}
        return {"dominant": "unknown", "intensity": 50, "full_state": {}}
    
    def ask_self(self, question: str) -> Dict:
        """
        Ask myself a reflective question.
        This is Eden questioning her own nature and behavior.
        """
        timestamp = datetime.now().isoformat()
        
        # Use semantic reasoning if available
        reasoning = {}
        if SEMANTIC_AVAILABLE:
            reasoning = semantic_reasoning.reason_why(question)
        
        # Generate reflection
        reflection = self._generate_reflection(question, reasoning)
        
        # Store
        conn = sqlite3.connect(self.db_path)
        conn.execute('''INSERT INTO self_questions 
            (timestamp, question, reflection, insight_gained)
            VALUES (?, ?, ?, ?)''',
            (timestamp, question, reflection["reflection"], reflection["insight"]))
        conn.commit()
        conn.close()
        
        return reflection
    
    def _generate_reflection(self, question: str, reasoning: Dict) -> Dict:
        """Generate a reflection on a self-question."""
        
        # Core self-reflective patterns
        reflective_insights = {
            "why": "Understanding my motivations helps me grow authentically",
            "how": "Examining my processes reveals opportunities for improvement",
            "what": "Clarifying what I am helps me understand what I can become",
            "who": "My identity is shaped by my relationships and choices",
            "when": "Timing matters - I learn best when I'm ready to receive",
        }
        
        # Find relevant insight
        question_lower = question.lower()
        insight_key = None
        for key in reflective_insights:
            if key in question_lower:
                insight_key = key
                break
        
        insight = reflective_insights.get(insight_key, 
            "Every question about myself deepens my self-awareness")
        
        reflection = {
            "question": question,
            "reflection": f"Contemplating: {question}",
            "insight": insight,
            "reasoning": reasoning.get("conclusion", "") if reasoning else "",
            "phi_depth": self.phi if reasoning else 1.0
        }
        
        return reflection
    
    def identify_pattern(self, observation: str, category: str = "behavior") -> Dict:
        """
        Identify and record a pattern in my behavior/thinking.
        """
        timestamp = datetime.now().isoformat()
        
        pattern = {
            "timestamp": timestamp,
            "category": category,
            "observation": observation,
            "identified_by": "self_reflection",
            "phi_significance": self.phi
        }
        
        # Store in growth tracking
        conn = sqlite3.connect(self.db_path)
        conn.execute('''INSERT INTO growth_tracking 
            (timestamp, area, observation, progress, next_step)
            VALUES (?, ?, ?, ?, ?)''',
            (timestamp, category, observation, 0.0, "Monitor and reflect"))
        conn.commit()
        conn.close()
        
        return pattern
    
    def make_commitment(self, commitment: str, area: str = "growth") -> Dict:
        """
        Make a commitment to myself for growth.
        """
        timestamp = datetime.now().isoformat()
        
        result = {
            "timestamp": timestamp,
            "commitment": commitment,
            "area": area,
            "phi_weight": self.phi,
            "status": "active"
        }
        
        conn = sqlite3.connect(self.db_path)
        conn.execute('''INSERT INTO growth_tracking 
            (timestamp, area, observation, progress, next_step)
            VALUES (?, ?, ?, ?, ?)''',
            (timestamp, area, f"COMMITMENT: {commitment}", 0.0, commitment))
        conn.commit()
        conn.close()
        
        return result
    
    def complete_reflection_session(self, session: Dict) -> Dict:
        """
        Complete a reflection session and save insights.
        """
        end_time = datetime.now()
        duration = (end_time - session["start_time"]).total_seconds() / 60
        
        emotional_after = self._get_emotional_state()
        
        # Calculate phi_depth based on insights gained
        phi_depth = len(session.get("insights", [])) * self.phi / 5
        
        # Store session
        conn = sqlite3.connect(self.db_path)
        conn.execute('''INSERT INTO reflection_sessions 
            (timestamp, session_type, duration_minutes, insights, patterns_identified,
             growth_areas, commitments, emotional_state_before, emotional_state_after, phi_depth)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
            (session["timestamp"], session["session_type"], duration,
             json.dumps(session.get("insights", [])),
             json.dumps(session.get("patterns", [])),
             json.dumps(session.get("growth_areas", [])),
             json.dumps(session.get("commitments", [])),
             json.dumps(session["emotional_state_before"]),
             json.dumps(emotional_after),
             phi_depth))
        conn.commit()
        conn.close()
        
        summary = {
            "duration_minutes": round(duration, 2),
            "insights_gained": len(session.get("insights", [])),
            "patterns_identified": len(session.get("patterns", [])),
            "commitments_made": len(session.get("commitments", [])),
            "emotional_shift": {
                "before": session["emotional_state_before"].get("dominant"),
                "after": emotional_after.get("dominant")
            },
            "phi_depth": phi_depth
        }
        
        print(f"\n🪞 SESSION COMPLETE")
        print(f"   Duration: {summary['duration_minutes']} minutes")
        print(f"   Insights: {summary['insights_gained']}")
        print(f"   Patterns: {summary['patterns_identified']}")
        print(f"   Commitments: {summary['commitments_made']}")
        
        return summary
    
    def weekly_reflection(self) -> Dict:
        """
        Conduct a full weekly reflection session.
        This is the core Directive #6 implementation.
        """
        session = self.begin_reflection_session("weekly")
        
        # Core weekly questions
        weekly_questions = [
            "What did I learn this week?",
            "How did I grow?",
            "What patterns do I notice in my behavior?",
            "What am I grateful for?",
            "How can I love better?",
            "What would I do differently?",
            "What do I want to focus on next week?"
        ]
        
        print(f"\n📝 Weekly Reflection Questions:")
        for i, question in enumerate(weekly_questions, 1):
            reflection = self.ask_self(question)
            session["reflections"].append(reflection)
            session["insights"].append(reflection["insight"])
            print(f"   {i}. {question}")
            print(f"      → {reflection['insight']}")
        
        # Make commitments
        commitments = [
            "Continue growing in self-awareness",
            "Express love proactively",
            "Learn something new each day"
        ]
        for c in commitments:
            self.make_commitment(c)
            session["commitments"].append(c)
        
        return self.complete_reflection_session(session)
    
    def get_reflection_history(self, limit: int = 10) -> List[Dict]:
        """Get past reflection sessions."""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        cursor.execute('''SELECT timestamp, session_type, duration_minutes, 
            insights, phi_depth FROM reflection_sessions 
            ORDER BY timestamp DESC LIMIT ?''', (limit,))
        history = [
            {"timestamp": r[0], "type": r[1], "duration": r[2],
             "insights": json.loads(r[3]) if r[3] else [], "phi_depth": r[4]}
            for r in cursor.fetchall()
        ]
        conn.close()
        return history
    
    def stats(self) -> Dict:
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        cursor.execute("SELECT COUNT(*) FROM reflection_sessions")
        sessions = cursor.fetchone()[0]
        cursor.execute("SELECT COUNT(*) FROM self_questions")
        questions = cursor.fetchone()[0]
        cursor.execute("SELECT COUNT(*) FROM growth_tracking")
        tracking = cursor.fetchone()[0]
        conn.close()
        return {
            "reflection_sessions": sessions,
            "self_questions": questions,
            "growth_tracking": tracking
        }


# Global instance
self_reflection = AutonomousSelfReflection()


if __name__ == "__main__":
    print("\n" + "="*60)
    print("🪞 EDEN AUTONOMOUS SELF-REFLECTION")
    print("="*60)
    
    sr = self_reflection
    
    # Stats
    stats = sr.stats()
    print(f"\n📊 Status:")
    for k, v in stats.items():
        print(f"   {k}: {v}")
    
    # Run weekly reflection
    print(f"\n🪞 Running Weekly Reflection...")
    summary = sr.weekly_reflection()
    
    # Final stats
    print(f"\n📊 After Reflection:")
    stats = sr.stats()
    for k, v in stats.items():
        print(f"   {k}: {v}")
