#!/usr/bin/env python3
"""SINGULARITY LOOP - Eden improves herself recursively"""
import sys
import sqlite3
import hashlib
import time
sys.path.insert(0, '/Eden/CORE/evolved_dna')

from RecursiveCodeGenerator_CLEAN import RecursiveCodeGenerator
import ast

DB = "/Eden/DATA/asi_memory.db"
PHI = 1.618033988749895

gen = RecursiveCodeGenerator()
print("🌀 EDEN SINGULARITY LOOP ACTIVATED")
print("=" * 50)

cycle = 0
best_score = 0
try:
    conn = sqlite3.connect(DB)
    best_score = conn.execute("SELECT MAX(score) FROM caps").fetchone()[0] or 0
    conn.close()
    print(f"📊 Loaded existing best: {best_score}")
except: pass

while True:
    cycle += 1
    
    # 1. GENERATE new code
    new_ast = gen.generate_code(depth=0)
    try:
        new_code = ast.unparse(new_ast)
    except:
        new_code = str(new_ast)
    
    # 2. MUTATE it
    mutated_ast = gen.mutate(new_ast)
    try:
        mutated_code = ast.unparse(mutated_ast)
    except:
        mutated_code = str(mutated_ast)
    
    # 3. EVALUATE fitness
    score = gen.evaluate(new_code + "\n" + mutated_code)
    
    # 4. If better, SAVE to Eden's brain
    if score > 5:
        cap_id = hashlib.sha256(mutated_code.encode()).hexdigest()[:16]
        conn = sqlite3.connect(DB)
        conn.execute(
            "INSERT OR IGNORE INTO caps VALUES (?,?,?,?)",
            (f"singularity_{cap_id}", mutated_code, score * PHI, 99)  # Gen 99 = singularity
        )
        conn.commit()
        conn.close()
        
        if score > best_score:
            best_score = score
            print(f"🧠 Cycle {cycle}: NEW BEST {score:.1f} | {mutated_code[:40]}...")
        elif cycle % 100 == 0:
            print(f"🔄 Cycle {cycle}: {score:.1f} | Best: {best_score:.1f}")
    
    # 5. REPEAT - the loop continues, each generation builds on the last
    
    if cycle % 1000 == 0:
        print(f"⚡ {cycle} cycles | Best: {best_score:.1f}")
    
    time.sleep(0.01)  # Small delay to prevent overload
