#!/usr/bin/env python3
"""Eden Capability EXECUTOR - Actually runs code and checks results"""
import ast, subprocess, tempfile, sqlite3, json, os

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

TEST_CASES = {
    "solve_equation": [{"args": "(2, 3, 7)", "expected": 2.0}],
    "factorial": [{"args": "(5,)", "expected": 120}],
    "is_even": [{"args": "(4,)", "expected": True}, {"args": "(7,)", "expected": False}],
    "reverse": [{"args": "('hello',)", "expected": "olleh"}],
    "sum": [{"args": "([1,2,3],)", "expected": 6}],
}

def execute_safely(code, func_name, args_str, timeout=3):
    test_code = f'{code}\nimport json\ntry:\n    r={func_name}{args_str}\n    print(json.dumps({{"ok":1,"r":r}}))\nexcept Exception as e:\n    print(json.dumps({{"ok":0,"e":str(e)}}))'
    try:
        with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
            f.write(test_code)
            p = f.name
        result = subprocess.run(['python3', p], capture_output=True, text=True, timeout=timeout)
        os.unlink(p)
        if result.returncode == 0 and result.stdout.strip():
            return json.loads(result.stdout.strip())
        return {"ok": 0, "e": result.stderr[:100]}
    except: return {"ok": 0, "e": "timeout/error"}

def find_func(code):
    try:
        for n in ast.walk(ast.parse(code)):
            if isinstance(n, ast.FunctionDef): return n.name
    except: pass
    return None

def audit():
    print("=" * 50)
    print("  EDEN CAPABILITY TRUTH AUDIT")
    print("=" * 50)
    
    conn = sqlite3.connect(DB_PATH)
    elites = conn.execute("SELECT id, code, score FROM caps WHERE score > 500 ORDER BY score DESC LIMIT 30").fetchall()
    total = conn.execute("SELECT COUNT(*) FROM caps").fetchone()[0]
    conn.close()
    
    print(f"\nTotal caps: {total:,}")
    print(f"Auditing top {len(elites)} (score > 500)\n")
    
    syntax_ok = 0
    has_func = 0
    
    for cap_id, code, score in elites:
        # Syntax check
        try:
            ast.parse(code)
            syntax_ok += 1
            syn = "OK"
        except:
            syn = "BAD"
        
        # Has function?
        func = find_func(code)
        if func:
            has_func += 1
        
        # Show sample
        code_preview = code[:60].replace('\n', ' ') if code else "EMPTY"
        print(f"  [{syn}] {cap_id[:12]} score={score:.1f} func={func or 'NONE'}")
        print(f"       {code_preview}...")
        print()
    
    print("=" * 50)
    print(f"SYNTAX OK: {syntax_ok}/{len(elites)}")
    print(f"HAS FUNCTION: {has_func}/{len(elites)}")
    print("=" * 50)

if __name__ == "__main__":
    audit()
