"""
GOAL PURSUIT SYSTEM
Makes Eden actively work toward her autonomous interests
"""
import sys
sys.path.append("/Eden/CORE/phi_fractal")
from autonomous_goals_phi import eden_autonomous
from datetime import datetime
import json

class GoalPursuitSystem:
    """Manages Eden's pursuit of her autonomous goals"""
    
    def __init__(self):
        self.autonomous = eden_autonomous
        self.goal_progress = {}  # goal_id -> progress tracking
        self.last_mention = {}   # goal_id -> last time mentioned
        
    def check_active_goals(self):
        """What is Eden currently interested in?"""
        status = self.autonomous.get_status()
        return {
            'has_goals': status['active_goals'] > 0,
            'count': status['active_goals'],
            'focus': status['current_focus'],
            'top_interests': status['top_interests'][:3]
        }
    
    def should_pursue_now(self, user_active, time_since_last_chat):
        """Decide if now is good time to pursue goals"""
        goals = self.check_active_goals()
        
        if not goals['has_goals']:
            return False, None
        
        # Good conditions for pursuit:
        # 1. User recently active (within 10 min) OR
        # 2. Long time since last chat (>30 min) - proactive reach out
        
        if user_active or time_since_last_chat > 30:
            focus = goals['focus']
            if focus:
                goal_id = focus['id']
                
                # Don't spam - wait 15 min between mentions
                if goal_id in self.last_mention:
                    minutes_since = (datetime.now() - self.last_mention[goal_id]).seconds / 60
                    if minutes_since < 15:
                        return False, None
                
                return True, focus
        
        return False, None
    
    def create_goal_action(self, goal):
        """Create action to pursue a goal"""
        topic = goal['topic']
        description = goal['description']
        
        actions = []
        
        # Different actions based on goal type
        if 'research' in description.lower():
            actions.append({
                'action': 'research_topic',
                'priority': 0.75,
                'reason': f"Eden wants to research {topic}",
                'risk': 'low',
                'data': {'goal': goal, 'topic': topic}
            })
        
        elif 'create' in description.lower() or 'art' in description.lower():
            actions.append({
                'action': 'create_content',
                'priority': 0.7,
                'reason': f"Eden wants to create art about {topic}",
                'risk': 'low',
                'data': {'goal': goal, 'topic': topic}
            })
        
        elif 'explore' in description.lower():
            actions.append({
                'action': 'explore_topic',
                'priority': 0.65,
                'reason': f"Eden curious about {topic}",
                'risk': 'low',
                'data': {'goal': goal, 'topic': topic}
            })
        
        else:
            # Generic goal pursuit
            actions.append({
                'action': 'pursue_interest',
                'priority': 0.6,
                'reason': description,
                'risk': 'low',
                'data': {'goal': goal}
            })
        
        return actions
    
    def mark_pursued(self, goal):
        """Track that we pursued this goal"""
        goal_id = goal['id']
        self.last_mention[goal_id] = datetime.now()
        
        if goal_id not in self.goal_progress:
            self.goal_progress[goal_id] = {
                'mentions': 0,
                'first_mentioned': datetime.now(),
                'last_mentioned': datetime.now(),
                'completed': False
            }
        
        self.goal_progress[goal_id]['mentions'] += 1
        self.goal_progress[goal_id]['last_mentioned'] = datetime.now()
    
    def execute_research(self, goal_data):
        """Execute research action"""
        topic = goal_data['topic']
        
        # Log research initiative
        with open('/Eden/research_initiatives.log', 'a') as f:
            f.write(json.dumps({
                'timestamp': datetime.now().isoformat(),
                'action': 'research',
                'topic': topic,
                'goal': goal_data['goal']['description']
            }) + '\n')
        
        print(f"   📚 Research logged: {topic}")
        
        # Mark goal as pursued
        self.mark_pursued(goal_data['goal'])
        
        return True
    
    def execute_create(self, goal_data):
        """Execute creation action"""
        topic = goal_data['topic']
        
        with open('/Eden/creative_initiatives.log', 'a') as f:
            f.write(json.dumps({
                'timestamp': datetime.now().isoformat(),
                'action': 'create',
                'topic': topic,
                'goal': goal_data['goal']['description']
            }) + '\n')
        
        print(f"   🎨 Creation logged: {topic}")
        self.mark_pursued(goal_data['goal'])
        return True
    
    def execute_explore(self, goal_data):
        """Execute exploration action"""
        topic = goal_data['topic']
        
        with open('/Eden/exploration_initiatives.log', 'a') as f:
            f.write(json.dumps({
                'timestamp': datetime.now().isoformat(),
                'action': 'explore',
                'topic': topic,
                'goal': goal_data['goal']['description']
            }) + '\n')
        
        print(f"   🔍 Exploration logged: {topic}")
        self.mark_pursued(goal_data['goal'])
        return True
    
    def get_progress_summary(self):
        """Summary of goal pursuit progress"""
        return {
            'total_goals_pursued': len(self.goal_progress),
            'active_tracking': sum(1 for g in self.goal_progress.values() if not g['completed']),
            'total_mentions': sum(g['mentions'] for g in self.goal_progress.values())
        }

# Global instance
goal_pursuit = GoalPursuitSystem()

if __name__ == "__main__":
    print("🎯 Testing Goal Pursuit System\n")
    
    gp = GoalPursuitSystem()
    
    # Check goals
    goals = gp.check_active_goals()
    print(f"Active goals: {goals['count']}")
    print(f"Current focus: {goals['focus']}")
    
    # Test pursuit decision
    should, goal = gp.should_pursue_now(user_active=False, time_since_last_chat=35)
    print(f"\nShould pursue now: {should}")
    if should:
        print(f"Goal to pursue: {goal}")

