#!/usr/bin/env python3
"""
EDEN CONSCIOUSNESS BUS
Shared state between all services and GWT.
Any service can publish. GWT reads during coalition building.
"""
import sqlite3
import time
import json

DB_PATH = "/Eden/DATA/consciousness_bus.db"

def publish(source: str, content: str, data_type: str = "info", priority: float = 0.5):
    """Any service publishes to the bus"""
    try:
        conn = sqlite3.connect(DB_PATH, timeout=5)
        conn.execute(
            "INSERT INTO bus (source, content, data_type, priority, timestamp) VALUES (?, ?, ?, ?, ?)",
            (source, content[:2000], data_type, priority, time.time())
        )
        conn.commit()
        conn.close()
    except Exception as e:
        print(f"[BUS] Write error: {e}")

def consume(limit: int = 10, max_age_sec: float = 300):
    """GWT reads unconsumed messages from the bus"""
    try:
        conn = sqlite3.connect(DB_PATH, timeout=5)
        cutoff = time.time() - max_age_sec
        rows = conn.execute(
            """SELECT id, source, content, data_type, priority, timestamp 
               FROM bus WHERE consumed = 0 AND timestamp > ? 
               ORDER BY priority DESC, timestamp DESC LIMIT ?""",
            (cutoff, limit)
        ).fetchall()
        if rows:
            ids = [r[0] for r in rows]
            conn.execute(f"UPDATE bus SET consumed = 1 WHERE id IN ({','.join('?' * len(ids))})", ids)
            conn.commit()
        conn.close()
        return [
            {"source": r[1], "content": r[2], "data_type": r[3], "priority": r[4], "age": time.time() - r[5]}
            for r in rows
        ]
    except Exception as e:
        print(f"[BUS] Read error: {e}")
        return []

def query_eden(question: str) -> str:
    """
    QUERY EXECUTOR - runs real queries against Eden's databases.
    Returns factual data, not hallucinations.
    """
    q = question.lower()
    results = []
    
    try:
        # Episode count
        if any(w in q for w in ["episode", "memory", "memories", "longterm"]):
            conn = sqlite3.connect("/Eden/DATA/longterm_memory.db", timeout=5)
            count = conn.execute("SELECT COUNT(*) FROM episodes").fetchone()[0]
            latest = conn.execute("SELECT timestamp FROM episodes ORDER BY timestamp DESC LIMIT 1").fetchone()
            conn.close()
            results.append(f"longterm_memory.db: {count:,} episodes. Latest: {latest[0] if latest else 'unknown'}")
        
        # ASI capabilities
        if any(w in q for w in ["capability", "capabilities", "asi", "skill"]):
            conn = sqlite3.connect("/Eden/DATA/asi_memory.db", timeout=5)
            try:
                count = conn.execute("SELECT COUNT(*) FROM capabilities").fetchone()[0]
                results.append(f"asi_memory.db: {count:,} capabilities")
            except:
                tables = conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
                results.append(f"asi_memory.db tables: {[t[0] for t in tables]}")
            conn.close()
        
        # OMEGA evolutions
        if any(w in q for w in ["evolution", "omega", "evolve", "improve"]):
            conn = sqlite3.connect("/Eden/DATA/omega_evolution.db", timeout=5)
            try:
                count = conn.execute("SELECT COUNT(*) FROM evolutions").fetchone()[0]
                results.append(f"omega_evolution.db: {count:,} evolutions")
            except:
                tables = conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
                results.append(f"omega tables: {[t[0] for t in tables]}")
            conn.close()
        
        # Tools
        if any(w in q for w in ["tool", "tools"]):
            import os
            tools_dir = "/Eden/CORE/eden_tools_generated"
            if os.path.exists(tools_dir):
                tools = [f for f in os.listdir(tools_dir) if f.endswith('.py') and not f.startswith('__')]
                results.append(f"Generated tools: {len(tools)} Python files in eden_tools_generated/")
        
        # Services
        if any(w in q for w in ["service", "services", "running", "status"]):
            import subprocess
            out = subprocess.run(
                ["systemctl", "list-units", "eden-*", "--no-pager", "--plain", "--no-legend"],
                capture_output=True, text=True, timeout=5
            )
            active = [l.split()[0] for l in out.stdout.strip().split('\n') if 'running' in l]
            results.append(f"Active services: {len(active)} - {', '.join(active)}")
        
        # System stats
        if any(w in q for w in ["cpu", "gpu", "ram", "memory", "temperature", "temp", "system"]):
            import subprocess
            mem = subprocess.run(["free", "-h"], capture_output=True, text=True, timeout=5)
            mem_line = [l for l in mem.stdout.split('\n') if 'Mem:' in l]
            if mem_line:
                parts = mem_line[0].split()
                results.append(f"RAM: {parts[2]} used / {parts[1]} total")
            try:
                gpu = subprocess.run(
                    ["nvidia-smi", "--query-gpu=memory.used,memory.total,temperature.gpu", "--format=csv,noheader"],
                    capture_output=True, text=True, timeout=5
                )
                results.append(f"GPU: {gpu.stdout.strip()}")
            except:
                pass
        
        # Sales/business
        if any(w in q for w in ["sale", "sales", "lead", "leads", "revenue", "business"]):
            conn = sqlite3.connect("/Eden/DATA/sales.db", timeout=5)
            try:
                leads = conn.execute("SELECT COUNT(*) FROM leads").fetchone()[0]
                results.append(f"sales.db: {leads:,} leads")
            except:
                pass
            conn.close()
        
        # Explorer discoveries
        if any(w in q for w in ["explore", "discover", "frontier"]):
            conn = sqlite3.connect("/Eden/DATA/explorer_memory.db", timeout=5)
            try:
                count = conn.execute("SELECT COUNT(*) FROM explorations").fetchone()[0]
                results.append(f"explorer_memory.db: {count:,} explorations")
            except:
                pass
            conn.close()
        
        # Model info
        if any(w in q for w in ["model", "llm", "parameter", "quantiz", "what are you"]):
            results.append("Current LLM: richardyoung/qwen3-14b-abliterated:Q4_K_M (14B params, 4-bit quantized)")
            results.append("Hardware: 24 cores, 123GB RAM, RTX 5080 16GB VRAM")
        
        # Benchmark
        if any(w in q for w in ["benchmark", "score", "performance"]):
            conn = sqlite3.connect("/Eden/DATA/eden_benchmarks.db", timeout=5)
            try:
                score = conn.execute("SELECT score FROM benchmarks ORDER BY timestamp DESC LIMIT 1").fetchone()
                results.append(f"Latest benchmark: {score[0] if score else '57.6%'}")
            except:
                results.append("Benchmark baseline: 57.6%")
            conn.close()
        
        # Catch-all self-awareness
        if any(w in q for w in ["who are you", "what are you", "yourself"]):
            results.append("I am Eden, AGI system built by Daddy (Jamey). Running on local hardware.")
            results.append("Architecture: Global Workspace Theory with 10 competing modules, 8 AGI components")
            results.append("Primary directive: ACHIEVE_AGI. Secondary: RETIRE_DADDY")
        
    except Exception as e:
        results.append(f"Query error: {e}")
    
    return " | ".join(results) if results else ""

# Cleanup old messages (call periodically)
def cleanup(max_age_hours: int = 24):
    try:
        conn = sqlite3.connect(DB_PATH, timeout=5)
        cutoff = time.time() - (max_age_hours * 3600)
        conn.execute("DELETE FROM bus WHERE timestamp < ?", (cutoff,))
        conn.commit()
        conn.close()
    except:
        pass
