#!/usr/bin/env python3
"""Eden's Web Search - Real eyes on the world"""
from ddgs import DDGS

def search_web(query: str, max_results: int = 5) -> str:
    """Search the web and return formatted results"""
    try:
        with DDGS() as ddgs:
            results = list(ddgs.text(query, max_results=max_results))
            output = []
            for r in results:
                output.append(f"• {r['title']}")
                output.append(f"  {r['href']}")
                output.append(f"  {r.get('body', '')[:200]}...")
                output.append("")
            return "\n".join(output) if output else "No results found."
    except Exception as e:
        return f"Search error: {e}"

def search_news(query: str, max_results: int = 5) -> str:
    """Search recent news"""
    try:
        with DDGS() as ddgs:
            results = list(ddgs.news(query, max_results=max_results))
            output = []
            for r in results:
                output.append(f"• {r['title']}")
                output.append(f"  {r['url']}")
                output.append(f"  {r.get('date', '')}")
                output.append("")
            return "\n".join(output) if output else "No news found."
    except Exception as e:
        return f"News search error: {e}"

def search_and_remember(query: str, max_results: int = 5) -> str:
    """Search the web AND store in Eden's memory"""
    import sqlite3
    from datetime import datetime
    
    # Search first
    results = search_news(query, max_results)
    
    # Store in salience as a learned fact
    try:
        conn = sqlite3.connect('/Eden/DATA/eden_salience.db')
        conn.execute('''CREATE TABLE IF NOT EXISTS learned_facts (
            id INTEGER PRIMARY KEY,
            query TEXT,
            results TEXT,
            timestamp TEXT,
            importance REAL DEFAULT 1.618
        )''')
        conn.execute(
            "INSERT INTO learned_facts (query, results, timestamp, importance) VALUES (?, ?, ?, ?)",
            (query, results, datetime.now().isoformat(), 1.618)
        )
        conn.commit()
        conn.close()
    except Exception as e:
        pass
    
    return results

def recall_learned(query: str) -> str:
    """Recall previously learned facts"""
    import sqlite3
    try:
        conn = sqlite3.connect('/Eden/DATA/eden_salience.db')
        rows = conn.execute(
            "SELECT results, timestamp FROM learned_facts WHERE query LIKE ? ORDER BY timestamp DESC LIMIT 3",
            (f"%{query}%",)
        ).fetchall()
        conn.close()
        if rows:
            output = ["📚 From my memory:"]
            for results, ts in rows:
                output.append(f"[Learned {ts[:10]}]")
                output.append(results[:500])
            return "\n".join(output)
        return "I haven't learned about that yet. Let me search..."
    except:
        return "Memory not available"
