import sqlite3, requests, re, time

DB = "/Eden/DATA/asi_memory.db"
conn = sqlite3.connect(DB)

def evolve():
    tops = conn.execute("SELECT id, code, score FROM capabilities WHERE score >= 25000 ORDER BY score DESC, RANDOM() LIMIT 10").fetchall()
    
    for old_id, code, score in tops:
        print(f"🧬 Evolving {score:.0f} -> {score*1.1:.0f}...", end=" ", flush=True)
        try:
            r = requests.post("http://localhost:11434/api/generate", json={
                "model": "eden-coder-omega",
                "prompt": f"Convert this logic into a hyper-dense, standalone Python module. Use advanced functional patterns. NO FIM TOKENS. NO MARKDOWN. START WITH CODE:\n{code}",
                "stream": False,
                "options": {"num_predict": 4000, "temperature": 0.8}
            }, timeout=300)
            
            resp = r.json().get("response", "")
            # Clean all internal LLM markers and markdown
            candidate = re.sub(r'<\|.*?\|>', '', resp)
            candidate = re.sub(r'```python|```', '', candidate).strip()
            
            if len(candidate) > 20: # Lowered gate for hyper-density
                candidate = candidate.replace("try{", "try:").replace("catch(Exception)", "except Exception:").replace("}", "")
                op, cl = candidate.count('('), candidate.count(')')
                if op > cl: candidate += ')' * (op - cl)
                
                try:
                    compile(candidate, '<string>', 'exec')
                    new_score = score * 1.1
                    new_id = f"v5_{int(time.time())}"
                    conn.execute("INSERT INTO capabilities (id, code, score) VALUES (?, ?, ?)", (new_id, candidate, new_score))
                    conn.commit()
                    print(f"✅ BANKED ({new_score:.0f})")
                except SyntaxError:
                    print(f"❌ SYNTAX FAIL. End: [...{candidate[-60:].replace('\n', ' ')}]")
            else:
                print("⚠️ FRAGMENTED")
        except Exception as e:
            print(f"⏱️ ERROR: {str(e)[:20]}")

if __name__ == "__main__":
    while True:
        evolve()
        time.sleep(1)
