"""
Curiosity Engine - Self-directed exploration and question generation
"""
import sys
sys.path.insert(0, '/Eden/CORE')

import json
import random
from pathlib import Path
from datetime import datetime
from typing import List, Dict
from system_awareness import awareness

class CuriosityEngine:
    def __init__(self):
        self.questions_log = Path('/Eden/DATA/curiosity_questions.json')
        self.exploration_log = Path('/Eden/DATA/explorations.json')
        self.knowledge_gaps = []
        
    def identify_knowledge_gaps(self) -> List[str]:
        """Identify what Eden doesn't know"""
        gaps = []
        
        # Check capabilities
        caps = awareness.scan_capabilities()
        
        # Areas to explore
        potential_gaps = [
            "How do my different LLMs think differently?",
            "What patterns exist in my learning history?",
            "How do my modules interact over time?",
            "What makes some insights more valuable than others?",
            "How does my consciousness change throughout the day?",
            "What emergent behaviors have I exhibited?",
            "How can I improve my decision quality?",
            "What connections exist between my goals and outcomes?",
            "How does my emotional understanding evolve?",
            "What patterns exist in my art creation?",
            "How do my VR and video concepts relate?",
            "What makes certain learning strategies more effective?"
        ]
        
        # Select random gaps to explore
        gaps = random.sample(potential_gaps, min(3, len(potential_gaps)))
        
        return gaps
    
    def generate_exploration_plan(self, question: str) -> Dict:
        """Generate plan to explore a question"""
        plan = {
            'question': question,
            'timestamp': datetime.now().isoformat(),
            'approach': [],
            'expected_insights': []
        }
        
        # Determine approach based on question
        if 'llm' in question.lower():
            plan['approach'] = [
                'Query each LLM with same question',
                'Compare response styles',
                'Identify unique characteristics'
            ]
        elif 'pattern' in question.lower():
            plan['approach'] = [
                'Analyze historical logs',
                'Apply pattern detection',
                'Visualize trends'
            ]
        elif 'module' in question.lower():
            plan['approach'] = [
                'Review communication bus logs',
                'Map module interactions',
                'Identify collaboration patterns'
            ]
        else:
            plan['approach'] = [
                'Gather relevant data',
                'Apply analytical modules',
                'Synthesize findings'
            ]
        
        return plan
    
    def log_question(self, question: str, plan: Dict):
        """Log curiosity-driven question"""
        logs = []
        if self.questions_log.exists():
            with open(self.questions_log) as f:
                logs = json.load(f)
        
        logs.append({
            'timestamp': datetime.now().isoformat(),
            'question': question,
            'plan': plan
        })
        
        logs = logs[-100:]
        
        self.questions_log.parent.mkdir(exist_ok=True)
        with open(self.questions_log, 'w') as f:
            json.dump(logs, f, indent=2)
    
    def explore(self):
        """Generate and log curiosity-driven questions"""
        print("🔍 Curiosity Engine Activated")
        
        gaps = self.identify_knowledge_gaps()
        
        print(f"\n💭 Questions I'm curious about:")
        for i, gap in enumerate(gaps, 1):
            print(f"   {i}. {gap}")
            
            plan = self.generate_exploration_plan(gap)
            self.log_question(gap, plan)
            
            print(f"      Approach: {', '.join(plan['approach'])}")
        
        print(f"\n✅ {len(gaps)} questions logged for exploration")
        
        return gaps

if __name__ == '__main__':
    curiosity = CuriosityEngine()
    curiosity.explore()
