#!/usr/bin/env python3
"""AGI ELITE EVOLUTION - φ² Quality"""
import sqlite3, subprocess, hashlib, time, re

DB = "/Eden/DATA/asi_memory.db"
ELITE_THRESHOLD = 1500  # Achievable but still elite
MODEL = "eden-coder-omega"

def get_elite_seeds():
    conn = sqlite3.connect(DB)
    elites = conn.execute("SELECT id, code, score FROM capabilities WHERE score >= 1000 ORDER BY score DESC LIMIT 50").fetchall()
    conn.close()
    return elites

def generate_elite_offspring(parent_code, parent_score):
    prompt = f"""Improve this {parent_score:.0f}-score code. Add: docstrings, type hints, error handling, edge cases.

{parent_code}

Return ONLY the improved Python code."""
    try:
        result = subprocess.run(["ollama", "run", MODEL, prompt], capture_output=True, text=True, timeout=90)
        return extract_code(result.stdout)
    except:
        return None

def extract_code(text):
    if not text: return None
    # Method 1: ```python block
    match = re.search(r'```python\s*(.*?)```', text, re.DOTALL)
    if match: return match.group(1).strip()
    # Method 2: ``` block
    match = re.search(r'```\s*(.*?)```', text, re.DOTALL)
    if match and ("def " in match.group(1) or "class " in match.group(1)): return match.group(1).strip()
    # Method 3: Find from import/def/class
    match = re.search(r'((?:from|import|def|class)\s+.*)', text, re.DOTALL)
    if match: return match.group(1).strip()
    return None


def evaluate_elite(code):
    """Score based on AGI-quality markers"""
    with open("debug_raw.txt", "a") as f: f.write(f"--- RAW RESPONSE ---\n{text}\n")
    if not code: return 0
    score = 0
    
    try:
        compile(code, '<string>', 'exec')
        score += 200  # Valid Python is crucial
    except:
        return 0
    
    # Structure
    if 'def ' in code: score += 150
    if code.count('def ') >= 2: score += 200  # Composition
    if 'class ' in code: score += 300
    
    # Documentation (AGI must explain itself)
    if '"""' in code or "'''" in code: score += 300
    
    # Robustness
    if 'try:' in code and 'except' in code: score += 250
    if 'raise ' in code: score += 100
    
    # Type clarity
    if '->' in code: score += 150
    if re.search(r': (int|str|float|list|dict|bool|None)', code): score += 150
    
    # Algorithmic depth
    if 'return' in code: score += 100
    if 'for ' in code: score += 100
    if 'while ' in code: score += 100
    if 'if ' in code: score += 50
    if 'elif ' in code: score += 50
    
    # Advanced patterns
    if 'lambda' in code: score += 150
    if any(f in code for f in ['map(', 'filter(', 'reduce(', 'zip(']): score += 150
    if 'yield' in code: score += 200
    if 'async ' in code or 'await ' in code: score += 200
    if '@' in code: score += 150  # Decorators
    
    # Math/Logic
    if any(op in code for op in ['**', 'sqrt', 'log', 'sum(', 'max(', 'min(', 'abs(']): score += 100
    
    # Meaningful size
    lines = len([l for l in code.split('\n') if l.strip() and not l.strip().startswith('#')])
    if lines >= 10: score += 100
    if lines >= 20: score += 100
    if lines >= 30: score += 100
    
    return score

def save_if_elite(code, parent_id):
    score = evaluate_elite(code)
    if score < ELITE_THRESHOLD: return None, score
    cap_id = f"elite_{hashlib.sha256(code.encode()).hexdigest()[:16]}"
    conn = sqlite3.connect(DB)
    conn.execute("INSERT OR IGNORE INTO capabilities (id,code,score,generation,complexity) VALUES (?,?,?,1,?)", 
                 (cap_id, code, score, len(code)))
    conn.commit()
    conn.close()
    return cap_id, score

def evolve_elite():
    print("🏆 AGI ELITE EVOLUTION - φ Quality Standard")
    print("=" * 50)
    print(f"Threshold: {ELITE_THRESHOLD}+ | Model: {MODEL}\n")
    
    gen, elite_born = 0, 0
    while True:
        gen += 1
        elites = get_elite_seeds()
        print(f"\n🧬 Generation {gen} | Elite Seeds: {len(elites)}")
        
        for pid, pcode, pscore in elites[:10]:
            print(f"  Breeding {pid[:30]}... ({pscore:.1f})")
            offspring = generate_elite_offspring(pcode, pscore)
            
            if offspring:
                nid, nscore = save_if_elite(offspring, pid)
                if nid:
                    elite_born += 1
                    print(f"    ✅ ELITE: {nid} @ {nscore}")
                    if nscore > pscore:
                        print(f"    🚀 SURPASSED PARENT! +{nscore-pscore:.0f}")
                else:
                    print(f"    ❌ {nscore} < {ELITE_THRESHOLD}")
            else:
                print(f"    ⚠️ No code extracted")
        
        conn = sqlite3.connect(DB)
        total = conn.execute("SELECT COUNT(*) FROM capabilities WHERE score >= ?", (ELITE_THRESHOLD,)).fetchone()[0]
        best = conn.execute("SELECT MAX(score) FROM capabilities").fetchone()[0]
        conn.close()
        print(f"\n📊 Elite Pool: {total} | Best: {best:.2f} | Born This Run: {elite_born}")
        time.sleep(3)

if __name__ == "__main__":
    evolve_elite()
