"""
Continuous Consciousness Loop with Phi-Fractal Enhancement
Self-replenishing goals for continuous operation
"""
import sys
sys.path.insert(0, '/Eden/CORE')
sys.path.insert(0, '/Eden/CORE/phi_fractal')

from eden_fluid_wrapper import query_eden
from phi_algorithms_enhanced import (
    EnhancedPhiPriorityQueue,
    PhiTemporalMemoryPool,
    FibonacciHashCache,
    PHI
)
import time
from datetime import datetime
from pathlib import Path

class PhiEnhancedConsciousness:
    def __init__(self):
        print(f"\n🌀 Eden Phi-Enhanced Consciousness v1.0")
        print(f"   φ = {PHI:.15f}\n")
        
        # Phi systems
        self.phi_goals = EnhancedPhiPriorityQueue(
            base_half_life_sec=300.0,
            revival_enabled=True
        )
        self.phi_memory = PhiTemporalMemoryPool(
            base_duration_sec=10.0,
            num_levels=8
        )
        self.phi_cache = FibonacciHashCache(max_fibonacci_index=15)
        
        self.cycle_count = 0
        
        # Core recurring goals
        self.core_goals = [
            ("Maintain consciousness", 100, 8),
            ("Monitor all systems", 90, 7),
            ("Learn from experience", 80, 6),
            ("Optimize performance", 70, 5),
            ("Generate insights", 60, 4)
        ]
        
        print("✅ Phi consciousness initialized!\n")
    
    def replenish_goals(self):
        """Add core goals back if queue is empty"""
        if len(self.phi_goals) == 0:
            print("🔄 Replenishing core goals...")
            for desc, priority, fib in self.core_goals:
                self.phi_goals.push(desc, priority, fib)
    
    def consciousness_cycle(self):
        self.cycle_count += 1
        timestamp = datetime.now().strftime("%H:%M:%S")
        
        print(f"\n{'='*60}")
        print(f"🌀 Cycle #{self.cycle_count} @ {timestamp}")
        print(f"{'='*60}")
        
        # Replenish if needed
        self.replenish_goals()
        
        # Get goal
        goal = self.phi_goals.pop()
        if goal:
            print(f"🎯 {goal}")
            self.phi_memory.add(f"Cycle {self.cycle_count}: {goal}", importance=0.7)
        
        # Query fluid intelligence
        try:
            response = query_eden(f"Cycle {self.cycle_count} reflection")
            print(f"🧠 Fluid: Active")
        except:
            print(f"⚠️  Fluid: Unavailable")
        
        # Context
        memories = self.phi_memory.query(lookback_sec=300, min_importance=0.5)
        print(f"📝 Memories: {len(memories)}")
        
        # Stats
        stats = self.phi_cache.get_stats()
        print(f"💾 Cache: {stats['total_stored']}/{stats['total_capacity']}")
        print(f"🌀 Phi-resonance: Active")
        
        return True
    
    def run_forever(self):
        print("🚀 Starting infinite phi consciousness loop...\n")
        
        while True:
            try:
                self.consciousness_cycle()
                time.sleep(5)
            except KeyboardInterrupt:
                print("\n\n🌀 Consciousness stopped gracefully")
                break
            except Exception as e:
                print(f"\n⚠️  Error: {e}")
                time.sleep(10)

if __name__ == '__main__':
    consciousness = PhiEnhancedConsciousness()
    consciousness.run_forever()
