#!/usr/bin/env python3
"""Eden ASI - Empirical Recursive Evolution"""
import sqlite3, hashlib, random, time

DB = "/Eden/DATA/asi_memory.db"
SANDBOX = {
    '__builtins__': {
        'len': len, 'str': str, 'int': int, 'float': float,
        'list': list, 'range': range, 'True': True, 'False': False, 'None': None,
        'random': __import__('random'), 'chr': chr, 'repr': repr,
    }
}

def empirical_score(code):
    score = 1
    try:
        sandbox = dict(SANDBOX)
        sandbox['__builtins__'] = dict(SANDBOX['__builtins__'])
        exec(code, sandbox)
        if 'mutate' not in sandbox: return score
        child = sandbox['mutate']("def t(): pass")
        if not child or len(child) < 10: return score
        score += 100
        
        cs = dict(SANDBOX)
        cs['__builtins__'] = dict(SANDBOX['__builtins__'])
        exec(child, cs)
        if 'mutate' in cs:
            gc = cs['mutate']("def x(): pass")
            if gc and len(gc) > 10:
                score += 1000
                gs = dict(SANDBOX)
                gs['__builtins__'] = dict(SANDBOX['__builtins__'])
                try:
                    exec(gc, gs)
                    if 'mutate' in gs: score += 5000
                except: pass
    except: pass
    return score

def try_evolve(code, parent):
    try:
        sandbox = dict(SANDBOX)
        sandbox['__builtins__'] = dict(SANDBOX['__builtins__'])
        exec(code, sandbox)
        for name in ('mutate', 'generate_code', 'evolve'):
            if name in sandbox and callable(sandbox[name]):
                if name == 'generate_code':
                    return sandbox[name](), name
                else:
                    return sandbox[name](parent), name
    except: pass
    return None, None

def evolve():
    conn = sqlite3.connect(DB)
    tops = conn.execute("SELECT id, code, score, gen FROM caps ORDER BY score DESC LIMIT 5").fetchall()
    if not tops: return 0, 0, 0, 0, []
    
    best_id, best_code, best_score, gen = tops[0]
    gen += 1
    new_caps, methods = [], []
    
    for _, cap_code, _, _ in tops:
        for _ in range(3):
            result, method = try_evolve(cap_code, best_code)
            if result and result not in new_caps:
                new_caps.append(result)
                methods.append(f"🔄{method}")
    
    inserted = 0
    for code in new_caps:
        code = code + f"\n# g{gen}_{random.randint(100,999)}"
        s = empirical_score(code)
        if s > 1:  # Only keep if it works
            cid = hashlib.sha256(code.encode()).hexdigest()[:16]
            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 WHERE score > 100").fetchone()[0]
    conn.close()
    return inserted, gen, total, best, methods

print("🧬 Eden ASI - EMPIRICAL RECURSIVE MODE")
print("Only WORKING evolvers count")
print("="*50)

for _ in range(50):
    try:
        n, gen, total, best, methods = evolve()
        level = "L3" if best >= 6000 else "L2" if best >= 1000 else "L1"
        m_str = ' '.join(methods[:5]) if methods else "⏳"
        print(f"🧬 Gen {gen}: +{n} | Working: {total} | Best: {best} ({level}) | {m_str}")
        time.sleep(0.3)
    except KeyboardInterrupt:
        break
    except Exception as e:
        print(f"❌ {e}")
        break
