#!/usr/bin/env python3
"""Advanced coding challenges for Eden"""
import sqlite3
import subprocess
import time

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

ADVANCED = [
    {
        "name": "binary_search",
        "prompt": "def binary_search(arr, target): # return index of target in sorted array, -1 if not found",
        "tests": [([1,2,3,4,5], 3, 2), ([1,2,3,4,5], 6, -1), ([1], 1, 0)],
    },
    {
        "name": "bubble_sort",
        "prompt": "def bubble_sort(arr): # return sorted array",
        "tests": [([3,1,2], [1,2,3]), ([5,4,3,2,1], [1,2,3,4,5]), ([], [])],
    },
    {
        "name": "gcd",
        "prompt": "def gcd(a, b): # return greatest common divisor",
        "tests": [(12, 8, 4), (17, 5, 1), (100, 25, 25)],
    },
    {
        "name": "count_vowels",
        "prompt": "def count_vowels(s): # return number of vowels in string",
        "tests": [("hello", 2), ("aeiou", 5), ("xyz", 0)],
    },
    {
        "name": "flatten_list",
        "prompt": "def flatten(lst): # flatten nested list [[1,2],[3]] -> [1,2,3]",
        "tests": [([[1,2],[3]], [1,2,3]), ([[1],[2],[3]], [1,2,3]), ([], [])],
    },
    {
        "name": "is_anagram",
        "prompt": "def is_anagram(s1, s2): # return True if s1 and s2 are anagrams",
        "tests": [("listen", "silent", True), ("hello", "world", False), ("", "", True)],
    },
]

def ask_eden(prompt):
    try:
        full_prompt = f"{prompt}\n\nWrite ONLY the Python function. No examples, no prints."
        r = subprocess.run(["ollama", "run", "eden-coder-omega", full_prompt],
                          capture_output=True, text=True, timeout=90)
        return r.stdout.strip()
    except:
        return None

def test_solution(code, tests):
    passed = 0
    try:
        if '```' in code:
            code = code.split('```')[1].replace('python', '')
        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 test in tests:
                try:
                    if len(test) == 3:
                        result = func(test[0], test[1])
                        if result == test[2]: passed += 1
                    elif len(test) == 2:
                        result = func(test[0])
                        if result == test[1]: passed += 1
                except:
                    pass
    except:
        pass
    return passed, len(tests)

def evolve(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!")
            conn = sqlite3.connect(DB)
            conn.execute("INSERT OR REPLACE INTO caps VALUES (?,?,?,?)",
                (f"verified_{task['name']}_{int(time.time())}", code, 1618.0, 100))
            conn.commit()
            conn.close()
            return True
    print(f"   ❌ Not solved")
    return False

print("🧠 EDEN ADVANCED CHALLENGES")
print("=" * 50)
solved = sum(1 for task in ADVANCED if evolve(task, 5))
print(f"\n{'='*50}\n🏆 SOLVED: {solved}/{len(ADVANCED)}")
