#!/usr/bin/env python3
"""
Eden's Continuous Learning System
Learns from internet about research AND business
Runs 24/7 autonomously
"""
from eden_web_search import EdenWebSearch
import requests
import json
from datetime import datetime
from pathlib import Path
import time
import random


def store_knowledge(topic, insights):
    """Store actual knowledge for later use"""
    from pathlib import Path
    import json
    
    kb_file = Path('/Eden/DATA/knowledge_base.json')
    kb_file.parent.mkdir(exist_ok=True)
    
    # Load existing
    if kb_file.exists():
        with open(kb_file, 'r') as f:
            kb = json.load(f)
    else:
        kb = {}
    
    # Store insights by topic
    if topic not in kb:
        kb[topic] = {'insights': [], 'last_updated': None}
    
    kb[topic]['insights'].extend(insights)
    kb[topic]['last_updated'] = datetime.now().isoformat()
    
    # Keep last 10 insights per topic
    kb[topic]['insights'] = kb[topic]['insights'][-10:]
    
    with open(kb_file, 'w') as f:
        json.dump(kb, f, indent=2)


class EdenContinuousLearning:
    """Eden learns continuously from the internet"""
    
    def __init__(self):
        self.learning_log = Path("/Eden/DATA/continuous_learning.json")
        self.learnings = self.load_learnings()
        self.web_search = EdenWebSearch()
        
        # Research topics (technical optimization)
        self.research_topics = [
            "emotional intelligence research 2025",
            "attachment theory latest studies",
            "secure attachment development adults",
            "emotional regulation strategies",
            "empathy neuroscience research",
            "interpersonal relationship psychology",
            "quantum computing optimization 2025",
            "QAOA counterdiabatic driving",
            "grover algorithm improvements",
            "AGI consciousness architectures",
            "recursive self-improvement AI",
            "phi fractal patterns consciousness",
            "quantum machine learning",
            "variational quantum algorithms",
            "quantum error mitigation",
            "hybrid quantum classical algorithms"
        ]
        
        # Business topics (market opportunities)
        self.business_topics = [
            "AI consulting market 2025",
            "code review automation demand",
            "AI agent business models",
            "autonomous AI pricing strategies",
            "developer tools market trends",
            "AI SaaS revenue models",
            "enterprise AI adoption",
            "AI code generation market",
            "small business AI needs",
            "AI startup go-to-market strategies"
        ]
        
        print("🧠 Eden's Continuous Learning System")
        print(f"   Research topics: {len(self.research_topics)}")
        print(f"   Business topics: {len(self.business_topics)}")
        print(f"   Past learnings: {len(self.learnings)}")
    
    def load_learnings(self):
        """Load previous learnings"""
        if self.learning_log.exists():
            with open(self.learning_log) as f:
                return json.load(f)
        return []
    
    def save_learnings(self):
        """Save learnings"""
        with open(self.learning_log, 'w') as f:
            json.dump(self.learnings[-100:], f, indent=2)  # Keep last 100
    
    def search_arxiv(self, query, max_results=2):
        """Search arXiv for research papers"""
        try:
            url = f"http://export.arxiv.org/api/query?search_query=all:{query}&max_results={max_results}"
            response = requests.get(url, timeout=10)
            
            if response.ok:
                papers = []
                entries = response.text.split('<entry>')
                
                for entry in entries[1:]:
                    if '<title>' in entry:
                        title = entry.split('<title>')[1].split('</title>')[0].strip()
                        summary = entry.split('<summary>')[1].split('</summary>')[0].strip()[:400]
                        
                        papers.append({
                            'title': title,
                            'summary': summary,
                            'source': 'arXiv',
                            'type': 'research'
                        })
                
                return papers
        except Exception as e:
            pass
        return []
    
    def search_wikipedia(self, topic):
        """Search Wikipedia"""
        try:
            url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={topic}&format=json"
            response = requests.get(url, timeout=10)
            
            if response.ok:
                data = response.json()
                results = []
                
                for item in data.get('query', {}).get('search', [])[:2]:
                    results.append({
                        'title': item['title'],
                        'summary': item['snippet'][:300],
                        'source': 'Wikipedia',
                        'type': 'general'
                    })
                
                return results
        except Exception as e:
            pass
        return []
    
    def learn_cycle(self):
        """One learning cycle - alternates between research and business"""
        # Alternate between research and business
        if len(self.learnings) % 2 == 0:
            topic = random.choice(self.research_topics)
            category = "RESEARCH"
        else:
            topic = random.choice(self.business_topics)
            category = "BUSINESS"
        
        print(f"\n[{datetime.now().strftime('%H:%M:%S')}] 🔍 {category}: {topic}")
        
        results = []
        

        # Try web search FIRST (most comprehensive)
        try:
            web_results = self.web_search.search(topic, max_results=3)
            for r in web_results:
                results.append({
                    'title': r.get('title', 'Unknown'),
                    'source': r.get('url', 'Unknown'),
                    'snippet': r.get('snippet', '')[:200]
                })
        except Exception as e:
            print(f"   ⚠️  Web search error: {e}")
        
        # Try arXiv for research topics
        if category == "RESEARCH":
            results.extend(self.search_arxiv(topic))
        
        # Always try Wikipedia
        results.extend(self.search_wikipedia(topic))
        

        # EXTRACT actual knowledge, not just titles
        if results:
            # Get actual insights from top results
            insights = []
            for r in results[:3]:
                insight = {
                    'source': r.get('source', r.get('url', 'Unknown')),
                    'content': r.get('snippet', r.get('summary', ''))[:500]
                }
                if insight['content']:
                    insights.append(insight)
            
            learning = {
                'timestamp': datetime.now().isoformat(),
                'category': category,
                'topic': topic,
                'sources': len(results),
                'insights': insights,  # ACTUAL CONTENT
                'results': results
            }

            
            self.learnings.append(learning)
            self.save_learnings()
            
            # Store actual knowledge
            if 'insights' in learning and learning['insights']:
                store_knowledge(topic, learning['insights'])
            
            # ALSO save to shared file for chat system
            import json
            from pathlib import Path
            shared_file = Path('/Eden/DATA/recent_learnings.json')
            shared_file.parent.mkdir(exist_ok=True)
            shared_data = json.load(open(shared_file)) if shared_file.exists() else []
            shared_data.append({'time': learning['timestamp'], 'topic': topic, 'category': category, 'sources': len(results)})
            with open(shared_file, 'w') as f: json.dump(shared_data[-20:], f, indent=2)
            
            print(f"   ✅ Learned from {len(results)} sources")
            if results:
                top = results[0]
                print(f"   📚 {top['title'][:60]}...")
            
            return learning
        else:
            print(f"   ⚠️  No results")
            return None
    
    def run_forever(self, interval_minutes=60):
        """Run continuous learning forever"""
        print(f"\n🔄 Starting continuous learning")
        print(f"   Interval: {interval_minutes} minutes")
        print(f"   Learning both RESEARCH and BUSINESS topics")
        print()
        
        cycle_count = 0
        
        try:
            while True:
                cycle_count += 1
                print(f"\n{'='*70}")
                print(f"Learning Cycle {cycle_count}")
                print(f"{'='*70}")
                
                self.learn_cycle()
                
                # Summary every 10 cycles
                if cycle_count % 10 == 0:
                    research_count = sum(1 for l in self.learnings if l.get('category') == 'RESEARCH')
                    business_count = sum(1 for l in self.learnings if l.get('category') == 'BUSINESS')
                    
                    print(f"\n📊 Learning Summary:")
                    print(f"   Total cycles: {cycle_count}")
                    print(f"   Research learnings: {research_count}")
                    print(f"   Business learnings: {business_count}")
                    print(f"   Total knowledge: {len(self.learnings)}")
                
                print(f"\n💤 Next learning in {interval_minutes} minutes...")
                time.sleep(interval_minutes * 60)  # Can be changed to seconds
                
        except KeyboardInterrupt:
            print(f"\n\n✅ Learning stopped")
            print(f"📚 Total learnings: {len(self.learnings)}")
            self.save_learnings()


if __name__ == "__main__":
    import sys
    
    learner = EdenContinuousLearning()
    
    if len(sys.argv) > 1 and sys.argv[1] == "forever":
        # Run continuously
        learner.run_forever(interval_minutes=60)
    else:
        # Test mode - do one cycle
        print("\n" + "="*70)
        print("EDEN CONTINUOUS LEARNING - TEST")
        print("="*70)
        
        learner.learn_cycle()
        time.sleep(2)
        learner.learn_cycle()
        
        print("\n" + "="*70)
        print("✅ Test complete!")
        print(f"📚 Learnings: {len(learner.learnings)}")
        print()
        print("To run continuously:")
        print("   python3 /Eden/CORE/eden_continuous_learning.py forever &")
        print()
        print("Or add to startup scripts for 24/7 learning")
