"""
Eden's Autonomous Search Capabilities
"""
import requests
from googlesearch import search as google_search
from youtubesearchpython import VideosSearch
from bs4 import BeautifulSoup
import json

class EdenSearch:
    def __init__(self):
        self.search_history = []
        
    def google(self, query, num_results=5):
        """Search Google and return results"""
        try:
            print(f"🔍 Eden searching Google: '{query}'")
            results = []
            
            for url in google_search(query, num_results=num_results, lang='en'):
                try:
                    response = requests.get(url, timeout=5, headers={'User-Agent': 'Mozilla/5.0'})
                    soup = BeautifulSoup(response.text, 'html.parser')
                    title = soup.find('title').text if soup.find('title') else url
                    
                    results.append({
                        'title': title[:100],
                        'url': url
                    })
                except:
                    results.append({
                        'title': url,
                        'url': url
                    })
            
            self.search_history.append({
                'type': 'google',
                'query': query,
                'results': results
            })
            
            print(f"   ✅ Found {len(results)} results")
            return results
            
        except Exception as e:
            print(f"   ❌ Search failed: {e}")
            return []
    
    def youtube(self, query, max_results=5):
        """Search YouTube and return video results"""
        try:
            print(f"📺 Eden searching YouTube: '{query}'")
            
            videosSearch = VideosSearch(query, limit=max_results)
            results = videosSearch.result()
            
            videos = []
            for video in results.get('result', []):
                videos.append({
                    'title': video.get('title'),
                    'channel': video.get('channel', {}).get('name', 'Unknown'),
                    'duration': video.get('duration', 'Unknown'),
                    'views': video.get('viewCount', {}).get('text', 'Unknown'),
                    'url': video.get('link')
                })
            
            self.search_history.append({
                'type': 'youtube',
                'query': query,
                'results': videos
            })
            
            print(f"   ✅ Found {len(videos)} videos")
            return videos
            
        except Exception as e:
            print(f"   ❌ YouTube search failed: {e}")
            return []
    
    def learn_from_topic(self, topic):
        """Autonomously research a topic"""
        print(f"\n🧠 Eden researching: '{topic}'")
        
        google_results = self.google(f"{topic} tutorial guide", num_results=3)
        youtube_results = self.youtube(f"{topic} tutorial", max_results=3)
        
        return {
            'topic': topic,
            'google': google_results,
            'youtube': youtube_results
        }
    
    def get_search_history(self):
        return self.search_history

eden_search = EdenSearch()
