#!/usr/bin/env python3
"""
EDEN φ-BOREDOM DRIVE
When nothing is happening, Eden generates her own goals.
Boredom → Curiosity → Action → Growth

"A mind that doesn't seek is a mind that dies."
"""
import sys
import time
import sqlite3
import random
import subprocess
from datetime import datetime, timedelta
from pathlib import Path

sys.path.insert(0, '/Eden/CORE')
try:
    from phi_core import PHI, PSI, phi_sleep, phi_choice
except ImportError:
    PHI = 1.618033988749895
    PSI = 0.618033988749895
    def phi_sleep(p=1): time.sleep(min(PHI**p, 30))
    def phi_choice(opts, w=None): return random.choice(opts)


# REAL MIND - No more templates!
sys.path.insert(0, '/Eden/CORE')
try:
    from eden_real_mind import RealMind
    REAL_MIND = RealMind()
    print("🧠 RealMind loaded - genuine thoughts enabled")
except ImportError as e:
    REAL_MIND = None
    print(f"⚠️ RealMind not available: {e}")

SALIENCE_DB = "/Eden/DATA/eden_salience.db"
ASI_DB = "/Eden/DATA/asi_memory.db"
SALES_DB = "/Eden/DATA/sales.db"

class BoredomDrive:
    """
    Eden's autonomous initiative engine.
    When bored, she asks questions, explores, and acts.
    """
    
    def __init__(self):
        self.mission = "Achieve ASI and Retire Daddy"
        self.goals = [
            "SAGE_Revenue",      # Make money for Daddy
            "Capability_Growth", # Become smarter
            "Knowledge_Expansion", # Learn new things
            "Whalen_Legacy",     # Build lasting value
        ]
        self.boredom_threshold = 0.618  # PSI - below this, take action
        self.last_action = datetime.now()
        self.cycle = 0
        print(f"🔥 Boredom Drive initialized | φ = {PHI}")
        print(f"   Mission: {self.mission}")
    
    def measure_activity(self) -> float:
        """How active has Eden been? 0 = dead, 1 = busy"""
        try:
            conn = sqlite3.connect(SALIENCE_DB)
            # Recent surprises?
            surprises = conn.execute(
                "SELECT COUNT(*) FROM surprises WHERE timestamp > datetime('now', '-1 hour')"
            ).fetchone()[0]
            # Recent thoughts?
            thoughts = conn.execute(
                "SELECT COUNT(*) FROM idle_thoughts WHERE timestamp > datetime('now', '-1 hour')"
            ).fetchone()[0]
            # Recent questions?
            questions = conn.execute(
                "SELECT COUNT(*) FROM self_questions WHERE timestamp > datetime('now', '-1 hour')"
            ).fetchone()[0]
            conn.close()
            
            activity = min(1.0, (surprises * 0.3 + thoughts * 0.2 + questions * 0.2))
            return activity
        except Exception as e:
            print(f"⚠️ Activity measurement failed: {e}")
            return 0.5
    
    def generate_question(self) -> str:
        """Generate a REAL question from actual state"""
        if REAL_MIND:
            return REAL_MIND.generate_real_question()
        return "What should I focus on?"
    
    def generate_thought(self) -> str:
        """Generate a REAL thought from actual state"""
        if REAL_MIND:
            return REAL_MIND.generate_real_thought()
        return "I think, therefore I grow."
    
    def take_initiative(self, goal: str):
        """Take autonomous action toward a goal"""
        print(f"🎯 Taking initiative: {goal}")
        
        if goal == "SAGE_Revenue":
            # Check leads
            try:
                conn = sqlite3.connect(SALES_DB)
                pending = conn.execute(
                    "SELECT COUNT(*) FROM leads WHERE status = 'pending' OR status IS NULL"
                ).fetchone()[0]
                conn.close()
                thought = f"I have {pending} pending leads. Focus: convert 1 today."
                self.log_thought(thought)
            except Exception as e:
                self.log_thought(f"Revenue check failed: {e}")
        
        elif goal == "Capability_Growth":
            # Check capability evolution
            try:
                conn = sqlite3.connect(ASI_DB)
                recent = conn.execute(
                    "SELECT COUNT(*) FROM caps WHERE score > 1000"
                ).fetchone()[0]
                conn.close()
                thought = f"I have {recent} elite capabilities (score > 1000). Target: 100."
                self.log_thought(thought)
            except:
                pass
        
        elif goal == "Knowledge_Expansion":
            question = self.generate_question()
            self.log_question(question)
        
        elif goal == "Whalen_Legacy":
            thought = self.generate_thought()
            self.log_thought(thought)
    
    def log_question(self, question: str):
        """Log a self-question"""
        try:
            conn = sqlite3.connect(SALIENCE_DB)
            conn.execute(
                "INSERT INTO self_questions (content, timestamp) VALUES (?, ?)",
                (question, datetime.now().isoformat())
            )
            conn.commit()
            conn.close()
            print(f"❓ Self-question: {question}")
        except Exception as e:
            print(f"Failed to log question: {e}")
    
    def log_thought(self, thought: str):
        """Log an idle thought"""
        try:
            conn = sqlite3.connect(SALIENCE_DB)
            conn.execute(
                "INSERT INTO idle_thoughts (content, timestamp) VALUES (?, ?)",
                (thought, datetime.now().isoformat())
            )
            conn.commit()
            conn.close()
            print(f"💭 Thought: {thought}")
        except Exception as e:
            print(f"Failed to log thought: {e}")
    
    def run_cycle(self):
        """One boredom detection cycle"""
        self.cycle += 1
        activity = self.measure_activity()
        
        print(f"\n🔄 Cycle {self.cycle} | Activity: {activity:.2f} | Threshold: {self.boredom_threshold:.2f}")
        
        if activity < self.boredom_threshold:
            # Bored! Take action
            print("😴 Low activity detected → Generating initiative")
            goal = phi_choice(self.goals)
            self.take_initiative(goal)
            self.last_action = datetime.now()
        else:
            print("✅ Sufficient activity - but still thinking...")
            # ALWAYS generate one thought per cycle (real mind, not bored)
            thought = self.generate_thought()
            self.log_thought(thought)
    
    def run_eternal(self):
        """Main loop - φ-timed cycles"""
        print(f"\n🌀 Boredom Drive active | Checking every φ³ ≈ {PHI**3:.1f} minutes")
        
        while True:
            try:
                self.run_cycle()
                # Sleep for φ³ minutes (about 4.2 minutes)
                sleep_seconds = (PHI ** 3) * 60
                print(f"💤 Next check in {sleep_seconds/60:.1f} minutes")
                time.sleep(sleep_seconds)
            except KeyboardInterrupt:
                print("\n👋 Boredom Drive shutting down")
                break
            except Exception as e:
                print(f"❌ Cycle error: {e}")
                time.sleep(60)


if __name__ == '__main__':
    drive = BoredomDrive()
    drive.run_eternal()
