#!/usr/bin/env python3
import sqlite3, hashlib, subprocess, re, time, zlib, random
import time
from pathlib import Path

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

def init():
    conn = sqlite3.connect(DB)
    conn.execute("CREATE TABLE IF NOT EXISTS caps (id TEXT PRIMARY KEY, code TEXT, score REAL, gen INTEGER)")
    conn.commit()
    conn.close()

def evolve():
    conn = sqlite3.connect(DB)
    
    # Seed if empty
    if conn.execute("SELECT COUNT(*) FROM caps").fetchone()[0] == 0:
        seed = '''class ASI:
    PHI = 1.618
    def think(self, x): return x * self.PHI if isinstance(x, (int,float)) else x
    def mutate(self, c): return c + "# evolved"
    def evolve(self): return "growing"
'''
        conn.execute("INSERT INTO caps VALUES (?,?,25,0)", (hashlib.sha256(seed.encode()).hexdigest()[:16], seed))
        conn.commit()
    
    # Get best
    best = conn.execute("SELECT code, gen FROM caps ORDER BY score DESC LIMIT 1").fetchone()
    code, gen = best[0], best[1] + 1
    
    # Mutate
    prompt = f"Add mutate(), evolve(), evaluate() to this. Seed {random.randint(0,9999)}:\n{code[:1500]}\nReturn ONLY Python code."
    
    try:
        r = subprocess.run(["ollama", "run", "eden-coder-omega", prompt], 
                          capture_output=True, text=True, timeout=120)
        m = re.search(r'```python\s*(.*?)```', r.stdout, re.DOTALL)
        if m:
            new_code = m.group(1).strip() + f"\n# gen{gen}_{random.randint(0,999)}"
            score = len(new_code)/50 + new_code.count('def ')*2 + new_code.count('class ')*3
            if 'mutate' in new_code: score += 5
            if 'evolve' in new_code: score += 5
            if 'exec' in new_code: score += 5
            cid = hashlib.sha256(new_code.encode()).hexdigest()[:16]
            conn.execute("INSERT OR IGNORE INTO caps VALUES (?,?,?,?)", (cid, new_code, score, gen))
            conn.commit()
            conn.close()
            return 1, gen, score
    except Exception as e:
        print(f"err: {e}")
    
    conn.close()
    return 0, gen, 0

init()
print("🧠 Eden Simple ASI")
while True:
    try:
        n, gen, score = evolve()
        total = sqlite3.connect(DB).execute("SELECT COUNT(*), MAX(score) FROM caps").fetchone()
        print(f"Gen {gen}: +{n} | Total: {total[0]} | Best: {total[1]:.1f}")
        time.sleep(3)
    except KeyboardInterrupt:
        print("Done")
        break
