#!/usr/bin/env python3
"""Push Eden to solve harder tasks with more attempts"""
import sqlite3
import subprocess
import time

DB = "/mnt/eden_ram/asi_memory.db"
PHI = 1.618033988749895

HARD_TASKS = [
    {
        "name": "fibonacci",
        "prompt": """Write a Python function fibonacci(n) that returns the nth Fibonacci number.
fibonacci(0) = 0
fibonacci(1) = 1  
fibonacci(5) = 5
fibonacci(10) = 55

def fibonacci(n):""",
        "tests": [(0, 0), (1, 1), (5, 5), (10, 55)],
    },
    {
        "name": "factorial",
        "prompt": """Write a Python function factorial(n) that returns n factorial.
factorial(0) = 1
factorial(1) = 1
factorial(5) = 120
factorial(7) = 5040

def factorial(n):""",
        "tests": [(0, 1), (1, 1), (5, 120), (7, 5040)],
    },
    {
        "name": "sum_digits",
        "prompt": """Write a Python function sum_digits(n) that returns sum of digits.
sum_digits(123) = 6
sum_digits(999) = 27

def sum_digits(n):""",
        "tests": [(123, 6), (999, 27), (10, 1)],
    },
    {
        "name": "is_palindrome",
        "prompt": """Write a Python function is_palindrome(s) that returns True if string is palindrome.
is_palindrome("radar") = True
is_palindrome("hello") = False

def is_palindrome(s):""",
        "tests": [("radar", True), ("hello", False), ("a", True)],
    },
]

def ask_eden(prompt):
    try:
        r = subprocess.run(
            ["ollama", "run", "eden-coder-omega", prompt + "\n\nOutput ONLY the complete function:"],
            capture_output=True, text=True, timeout=90
        )
        return r.stdout.strip()
    except:
        return None

def extract_function(code):
    """Extract just the function definition"""
    lines = []
    in_func = False
    for line in code.split('\n'):
        if line.strip().startswith('def '):
            in_func = True
        if in_func:
            lines.append(line)
            if line.strip() and not line.startswith(' ') and not line.startswith('def'):
                break
    return '\n'.join(lines)

def test_solution(code, tests):
    passed = 0
    try:
        # Clean the code
        if '```' in code:
            code = code.split('```')[1].replace('python', '').strip()
        
        namespace = {}
        exec(code, namespace)
        
        func = None
        for v in namespace.values():
            if callable(v) and not str(v).startswith('<built'):
                func = v
                break
        
        if func:
            for inp, expected in tests:
                try:
                    result = func(inp)
                    if result == expected:
                        passed += 1
                except:
                    pass
    except Exception as e:
        pass
    
    return passed, len(tests)

def evolve_hard(task, attempts=5):
    print(f"\n🎯 {task['name']}:")
    
    for attempt in range(attempts):
        code = ask_eden(task['prompt'])
        if not code:
            continue
        
        passed, total = test_solution(code, task['tests'])
        
        if passed > 0:
            print(f"   Attempt {attempt+1}: {passed}/{total} ✓")
        
        if passed == total:
            print(f"   ✅ SOLVED!")
            # Save to DB
            conn = sqlite3.connect(DB)
            conn.execute("INSERT OR REPLACE INTO caps VALUES (?,?,?,?)",
                (f"verified_{task['name']}_{int(time.time())}", code, 1000 * PHI, 100))
            conn.commit()
            conn.close()
            return True, code
    
    print(f"   ❌ Not solved yet")
    return False, None

print("🧠 EDEN HARDER CHALLENGES")
print("=" * 50)

solved = 0
for task in HARD_TASKS:
    success, code = evolve_hard(task, attempts=5)
    if success:
        solved += 1

print("\n" + "=" * 50)
print(f"🏆 SOLVED: {solved}/{len(HARD_TASKS)}")
