#!/usr/bin/env python3
"""
Eden ASI - PURE RECURSIVE MODE
No LLM - evolved code ONLY drives evolution
True self-improvement
"""
import sqlite3, hashlib, random, time

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

def try_execute_evolved(code, parent_code):
    try:
        sandbox = {
            '__builtins__': {
                'len': len, 'str': str, 'int': int, 'float': float,
                'list': list, 'dict': dict, 'range': range,
                'isinstance': isinstance, 'type': type, 'hasattr': hasattr,
                'getattr': getattr, 'callable': callable,
                'True': True, 'False': False, 'None': None,
                'random': __import__('random'),
            }
        }
        exec(code, sandbox)
        
        # Check functions
        for name in ('mutate', 'generate_code', 'evolve'):
            if name in sandbox and callable(sandbox[name]):
                try:
                    if name == 'mutate':
                        result = sandbox[name](parent_code)
                        if result and len(result) > 20:
                            return result, "mutate"
                    elif name == 'generate_code':
                        result = sandbox[name]()
                        if result and len(str(result)) > 20:
                            return str(result), "generate"
                    elif name == 'evolve':
                        result = sandbox[name](parent_code)
                        if result and len(result) > 20:
                            return result, "evolve"
                except: pass
        
        # Check classes
        for name, obj in sandbox.items():
            if isinstance(obj, type):
                try:
                    instance = obj()
                    for method in ('mutate', 'generate_code', 'evolve'):
                        if hasattr(instance, method):
                            fn = getattr(instance, method)
                            if method == 'generate_code':
                                result = fn()
                            else:
                                result = fn(parent_code)
                            if result and len(str(result)) > 20:
                                return str(result), method
                except: pass
    except: pass
    return None, None

def score(code):
    s = len(code) / 50
    s += code.count('def ') * 2
    s += code.count('class ') * 3
    if 'mutate' in code.lower(): s += 10
    if 'evolve' in code.lower(): s += 10
    if 'generate' in code.lower(): s += 10
    if '1.618' in code or 'phi' in code.lower(): s += 5
    return s

def evolve():
    conn = sqlite3.connect(DB)
    
    tops = conn.execute("SELECT code, gen FROM caps ORDER BY score DESC LIMIT 5").fetchall()
    if not tops:
        conn.close()
        return 0, 0, 0, 0, []
    
    best_code, gen = tops[0][0], tops[0][1] + 1
    new_caps = []
    methods = []
    
    # PURE RECURSIVE: Use evolved code to generate new code
    for cap_code, _ in tops:
        result, method = try_execute_evolved(cap_code, best_code)
        if result:
            new_caps.append(result)
            methods.append(f"🔄{method}")
            
        # Also try generating multiple times
        for _ in range(3):
            result2, method2 = try_execute_evolved(cap_code, random.choice([c[0] for c in tops]))
            if result2 and result2 not in new_caps:
                new_caps.append(result2)
                methods.append(f"🔄{method2}")
    
    # Store new capabilities
    inserted = 0
    for code in new_caps:
        code = code + f"\n# g{gen}_{random.randint(100,999)}"
        cid = hashlib.sha256(code.encode()).hexdigest()[:16]
        s = score(code)
        try:
            conn.execute("INSERT OR IGNORE INTO caps VALUES (?,?,?,?)", (cid, code, s, gen))
            inserted += 1
        except: pass
    
    conn.commit()
    best = conn.execute("SELECT MAX(score) FROM caps").fetchone()[0] or 0
    total = conn.execute("SELECT COUNT(*) FROM caps").fetchone()[0]
    conn.close()
    
    return inserted, gen, total, best, methods

print("🌀 Eden ASI - PURE RECURSIVE MODE")
print("No LLM - evolved code drives ALL evolution")
print("="*50)

gen_count = 0
while gen_count < 100:  # Run 100 generations
    try:
        n, gen, total, best, methods = evolve()
        m_str = ' '.join(methods) if methods else "⏳"
        print(f"🔄 Gen {gen}: +{n} | Total: {total} | Best: {best:.1f} | {m_str}")
        gen_count += 1
        time.sleep(0.5)
    except KeyboardInterrupt:
        print("\n🛑 Stopped"); break
    except Exception as e:
        print(f"❌ {e}"); break

print(f"\n✅ Completed {gen_count} generations of pure recursive evolution")
