"""
EDEN QUALITY EVOLUTION v1.0
Every capability is verified before acceptance.
"Better 100 diamonds than 10,000 pebbles."
"""
import sys
sys.path.insert(0, '/Eden/CORE')

from eden_agi import EdenAGI
import sqlite3
import re
import time
from datetime import datetime

class QualityEvolution:
    """Generate high-quality capabilities with strict verification"""
    
    def __init__(self):
        self.agi = EdenAGI()
        self.db = "/Eden/DATA/asi_memory.db"
        self.min_iq = 3000  # Minimum IQ to accept
        self.max_length = 200  # Maximum code length
        self.log_file = "/Eden/DATA/quality_evolution_log.jsonl"
        
        print(f"🧬 Quality Evolution initialized")
        print(f"   Min IQ: {self.min_iq}")
        print(f"   Max length: {self.max_length}c")
    
    def get_existing_atoms(self):
        """Get list of existing atom names to avoid duplicates"""
        conn = sqlite3.connect(self.db)
        existing = conn.execute("SELECT id FROM capabilities WHERE id LIKE 'verified_%'").fetchall()
        conn.close()
        return set(row[0] for row in existing)
    
    def generate_candidate(self, category):
        """Generate a candidate atom for a category"""
        prompts = {
            'math': "Create a tiny Python math function (factorial, permutation, combination, sqrt, log, etc). ONE function, under 100 chars, no imports.",
            'string': "Create a tiny Python string function (reverse, capitalize, count vowels, remove spaces, etc). ONE function, under 100 chars.",
            'list': "Create a tiny Python list function (rotate, interleave, partition, dedupe, etc). ONE function, under 100 chars.",
            'logic': "Create a tiny Python logic function (xor, nand, implies, iff, etc). ONE function, under 100 chars.",
            'security': "Create a tiny Python security function (validate email, check password strength, mask data, etc). ONE function, under 100 chars.",
            'utility': "Create a tiny Python utility function (retry, timeout, cache key, etc). ONE function, under 100 chars.",
        }
        
        prompt = prompts.get(category, prompts['utility'])
        prompt += "\nReturn ONLY the def line and body. No explanation. No markdown."
        
        response = self.agi.think(prompt, 150)
        
        # Extract function
        match = re.search(r'(def \w+\([^)]*\):[^\n]*(?:\n[ \t]+[^\n]+)*)', response)
        if match:
            return match.group(1).strip()
        return None
    
    def validate(self, code):
        """Comprehensive validation"""
        checks = {
            'syntax': False,
            'has_function': False,
            'length_ok': False,
            'iq_ok': False,
            'not_duplicate': False,
            'executes': False
        }
        
        # 1. Syntax check
        try:
            compile(code, '<string>', 'exec')
            checks['syntax'] = True
        except:
            return checks, "Syntax error"
        
        # 2. Has function
        if re.match(r'^def \w+', code):
            checks['has_function'] = True
        else:
            return checks, "No function definition"
        
        # 3. Length check
        if len(code) <= self.max_length:
            checks['length_ok'] = True
        else:
            return checks, f"Too long: {len(code)}c > {self.max_length}c"
        
        # 4. IQ check
        iq = 4235 / len(code) * 100
        if iq >= self.min_iq:
            checks['iq_ok'] = True
        else:
            return checks, f"IQ too low: {iq:.0f} < {self.min_iq}"
        
        # 5. Duplicate check
        existing = self.get_existing_atoms()
        func_name = re.search(r'def (\w+)', code).group(1)
        if not any(func_name in e for e in existing):
            checks['not_duplicate'] = True
        else:
            return checks, f"Duplicate: {func_name}"
        
        # 6. Execution test
        try:
            exec(code)
            checks['executes'] = True
        except:
            return checks, "Execution failed"
        
        return checks, "PASSED"
    
    def save_atom(self, code, category):
        """Save verified atom to database"""
        func_name = re.search(r'def (\w+)', code).group(1)
        atom_id = f"verified_{func_name}"
        iq = 4235 / len(code) * 100
        
        conn = sqlite3.connect(self.db)
        conn.execute(
            "INSERT OR REPLACE INTO capabilities (id, code, score) VALUES (?, ?, ?)",
            (atom_id, code, 4235)
        )
        conn.commit()
        conn.close()
        
        # Log
        import json
        with open(self.log_file, 'a') as f:
            f.write(json.dumps({
                'timestamp': datetime.now().isoformat(),
                'id': atom_id,
                'category': category,
                'length': len(code),
                'iq': round(iq),
                'status': 'accepted'
            }) + '\n')
        
        return atom_id, iq
    
    def evolve_one(self, category='utility'):
        """Generate and validate ONE high-quality atom"""
        print(f"\n🧬 Generating {category} atom...")
        
        # Generate
        code = self.generate_candidate(category)
        if not code:
            print(f"   ❌ Generation failed")
            return None
        
        print(f"   📝 Candidate: {code[:60]}...")
        print(f"   📏 Length: {len(code)}c")
        
        # Validate
        checks, status = self.validate(code)
        
        print(f"   🔍 Validation:")
        for check, passed in checks.items():
            print(f"      {'✅' if passed else '❌'} {check}")
        
        if status == "PASSED":
            atom_id, iq = self.save_atom(code, category)
            print(f"   ✅ ACCEPTED: {atom_id} (IQ: {iq:.0f})")
            return atom_id
        else:
            print(f"   ❌ REJECTED: {status}")
            return None
    
    def evolve_batch(self, count=10, categories=None):
        """Generate multiple quality atoms"""
        if categories is None:
            categories = ['math', 'string', 'list', 'logic', 'security', 'utility']
        
        print(f"🧬 QUALITY EVOLUTION: Generating {count} atoms\n")
        
        accepted = 0
        rejected = 0
        
        for i in range(count):
            category = categories[i % len(categories)]
            result = self.evolve_one(category)
            
            if result:
                accepted += 1
            else:
                rejected += 1
            
            # Brief pause to not overwhelm Ollama
            time.sleep(2)
        
        print(f"\n{'='*50}")
        print(f"📊 RESULTS:")
        print(f"   Accepted: {accepted}")
        print(f"   Rejected: {rejected}")
        print(f"   Success rate: {accepted/(accepted+rejected)*100:.0f}%")
        
        # Show new total
        conn = sqlite3.connect(self.db)
        total = conn.execute("SELECT COUNT(*) FROM capabilities WHERE id LIKE 'verified_%'").fetchone()[0]
        conn.close()
        print(f"   Total atoms: {total}")
        print(f"   Omni progress: {(total+13)/1000*100:.1f}%")  # +13 for metas/integrations

# === MAIN ===
if __name__ == "__main__":
    qe = QualityEvolution()
    
    print("\n" + "="*50)
    print("🧬 QUALITY EVOLUTION TEST")
    print("="*50)
    
    # Generate 5 quality atoms as test
    qe.evolve_batch(5)
