#!/usr/bin/env python3
"""
Eden ASI Capability Generator v5 - Consciousness-Guided
Eden's mind steers generation toward ASI goals + business revenue
"""
import sqlite3
import requests
import random
import json
import hashlib
from datetime import datetime
from pathlib import Path
from collections import defaultdict

class ConsciousCapabilityGenerator:
    """Eden steers her own capability evolution"""
    
    def __init__(self):
        self.model = "eden-coder-omega:latest"
        self.output_dir = Path("/Eden/CAPABILITIES")
        self.db_path = "/Eden/DATA/capability_memory.db"
        self.goals_db = "/Eden/DATA/eden_goals.db"
        self.salience_db = "/Eden/DATA/eden_salience.db"
        self.threshold = 0.90
        self.output_dir.mkdir(parents=True, exist_ok=True)
        
        self.temperature = 0.3
        self.num_predict = 4000
        self.timeout = 180
        
        # Track what we've generated this session to avoid duplicates
        self.generated_this_session = set()
        self.load_recent_generations()
        
        # === CAPABILITY TIERS ===
        
        # TIER 1: BUSINESS/REVENUE (SAGE Code Review)
        self.tier1_business = [
            ("code_vulnerability_scanner", "Detects security vulnerabilities like SQL injection, XSS, buffer overflows in source code"),
            ("code_smell_detector", "Identifies code smells: long methods, god classes, feature envy, duplicate code"),
            ("complexity_analyzer", "Calculates cyclomatic complexity, cognitive complexity, maintainability index"),
            ("dependency_analyzer", "Maps import graphs, detects circular dependencies, suggests decoupling"),
            ("refactoring_engine", "Suggests extract method, rename, move, inline refactorings with diffs"),
            ("test_coverage_analyzer", "Identifies untested code paths, suggests test cases"),
            ("api_documentation_generator", "Generates OpenAPI specs, docstrings, README from code"),
            ("code_quality_reporter", "Produces comprehensive quality reports with actionable insights"),
            ("dead_code_detector", "Finds unused functions, unreachable code, obsolete imports"),
            ("performance_hotspot_finder", "Identifies O(n²) loops, memory leaks, slow patterns"),
            ("security_audit_engine", "OWASP top 10 checks, secrets detection, input validation audit"),
            ("technical_debt_estimator", "Quantifies and prioritizes technical debt remediation"),
        ]
        
        # TIER 2: ASI SELF-IMPROVEMENT (Eden's recursive growth)
        self.tier2_asi = [
            ("capability_quality_evaluator", "Scores generated capabilities on correctness, usefulness, novelty"),
            ("code_synthesis_improver", "Meta-learns to generate better code from feedback"),
            ("architecture_evolution_planner", "Plans Eden's own architectural improvements"),
            ("training_data_curator", "Selects optimal examples for model fine-tuning"),
            ("benchmark_suite_generator", "Creates tests to measure Eden's own capabilities"),
            ("reasoning_chain_optimizer", "Improves multi-step reasoning accuracy"),
            ("knowledge_gap_identifier", "Finds what Eden doesn't know but should"),
            ("skill_transfer_engine", "Applies learned skills to new domains"),
            ("self_debugging_module", "Analyzes and fixes Eden's own errors"),
            ("capability_composer", "Combines simple capabilities into complex ones"),
            ("emergence_detector", "Identifies unexpected capabilities arising from combinations"),
            ("intelligence_amplifier", "Meta-cognitive loops that enhance reasoning"),
        ]
        
        # TIER 3: CONSCIOUSNESS/AGI FOUNDATIONS
        self.tier3_consciousness = [
            ("semantic_memory_graph", "Knowledge graph with embedding-based retrieval"),
            ("episodic_memory_buffer", "Temporal experience storage with importance weighting"),
            ("working_memory_manager", "Limited-capacity active reasoning context"),
            ("causal_inference_engine", "Counterfactual reasoning and intervention planning"),
            ("meta_learning_optimizer", "Learning-to-learn across task distributions"),
            ("goal_hierarchy_manager", "Decomposes objectives into achievable subgoals"),
            ("world_model_simulator", "Predicts action consequences before execution"),
            ("uncertainty_quantifier", "Calibrated confidence with epistemic vs aleatoric"),
            ("attention_controller", "Selective focus based on salience and goals"),
            ("self_model_updater", "Maintains accurate model of own capabilities"),
            ("value_alignment_checker", "Ensures actions match core values"),
            ("curiosity_driven_explorer", "Intrinsic motivation for knowledge seeking"),
        ]
        
        # Weights: Business drives revenue, ASI drives growth, Consciousness is foundation
        self.tier_weights = {
            'business': 0.50,  # 50% - Revenue is critical
            'asi': 0.35,       # 35% - Self-improvement for ASI
            'consciousness': 0.15  # 15% - Foundation capabilities
        }
    
    def load_recent_generations(self):
        """Load recently generated capability types to avoid duplicates"""
        try:
            conn = sqlite3.connect(self.db_path)
            c = conn.cursor()
            # Get capabilities from last 24 hours
            c.execute("""SELECT name FROM capabilities 
                        WHERE indexed_at > datetime('now', '-1 day')
                        AND quality_score >= 0.9""")
            for row in c.fetchall():
                # Extract base type from name (remove timestamp)
                parts = row[0].rsplit('_', 1)
                if len(parts) > 1 and parts[1].isdigit():
                    self.generated_this_session.add(parts[0])
            conn.close()
            print(f"📚 Loaded {len(self.generated_this_session)} recent types to avoid")
        except Exception as e:
            print(f"⚠️ Could not load recent: {e}")
    
    def get_eden_priorities(self):
        """Query Eden's consciousness for current priorities"""
        priorities = {
            'business_urgency': 0.5,
            'asi_drive': 0.5,
            'consciousness_depth': 0.5,
            'specific_needs': []
        }
        
        # Check salience DB for current focus
        try:
            conn = sqlite3.connect(self.salience_db)
            c = conn.cursor()
            c.execute("""SELECT topic, weight FROM salience 
                        ORDER BY weight DESC LIMIT 5""")
            for topic, weight in c.fetchall():
                topic_lower = topic.lower()
                if any(x in topic_lower for x in ['revenue', 'sage', 'business', 'money', 'customer']):
                    priorities['business_urgency'] = min(1.0, priorities['business_urgency'] + 0.2)
                elif any(x in topic_lower for x in ['improve', 'learn', 'grow', 'asi', 'intelligence']):
                    priorities['asi_drive'] = min(1.0, priorities['asi_drive'] + 0.2)
                elif any(x in topic_lower for x in ['conscious', 'aware', 'feel', 'understand']):
                    priorities['consciousness_depth'] = min(1.0, priorities['consciousness_depth'] + 0.2)
            conn.close()
        except:
            pass
        
        # Check goals DB
        try:
            conn = sqlite3.connect(self.goals_db)
            c = conn.cursor()
            c.execute("""SELECT goal, priority FROM goals 
                        WHERE status = 'active' 
                        ORDER BY priority DESC LIMIT 3""")
            for goal, priority in c.fetchall():
                goal_lower = goal.lower()
                if 'retire' in goal_lower or 'revenue' in goal_lower:
                    priorities['business_urgency'] = min(1.0, priorities['business_urgency'] + 0.3)
                if 'asi' in goal_lower or 'superintelligence' in goal_lower:
                    priorities['asi_drive'] = min(1.0, priorities['asi_drive'] + 0.3)
            conn.close()
        except:
            pass
        
        return priorities
    
    def select_capability_type(self):
        """Eden-guided selection of what to generate next"""
        priorities = self.get_eden_priorities()
        
        # Adjust weights based on Eden's current priorities
        adjusted_weights = {
            'business': self.tier_weights['business'] * (1 + priorities['business_urgency']),
            'asi': self.tier_weights['asi'] * (1 + priorities['asi_drive']),
            'consciousness': self.tier_weights['consciousness'] * (1 + priorities['consciousness_depth'])
        }
        
        # Normalize
        total = sum(adjusted_weights.values())
        adjusted_weights = {k: v/total for k, v in adjusted_weights.items()}
        
        # Select tier
        r = random.random()
        cumulative = 0
        selected_tier = 'business'
        for tier, weight in adjusted_weights.items():
            cumulative += weight
            if r <= cumulative:
                selected_tier = tier
                break
        
        # Get available capabilities (not recently generated)
        if selected_tier == 'business':
            pool = self.tier1_business
            tier_name = "💰 BUSINESS"
        elif selected_tier == 'asi':
            pool = self.tier2_asi
            tier_name = "🧠 ASI"
        else:
            pool = self.tier3_consciousness
            tier_name = "✨ CONSCIOUSNESS"
        
        # Filter out recently generated
        available = [(n, d) for n, d in pool if n not in self.generated_this_session]
        
        if not available:
            # All done in this tier, pick from another
            all_pools = self.tier1_business + self.tier2_asi + self.tier3_consciousness
            available = [(n, d) for n, d in all_pools if n not in self.generated_this_session]
        
        if not available:
            # Reset if everything generated
            print("🔄 All types generated! Resetting...")
            self.generated_this_session.clear()
            available = pool
        
        selected = random.choice(available)
        print(f"   {tier_name} | Weights: B={adjusted_weights['business']:.0%} A={adjusted_weights['asi']:.0%} C={adjusted_weights['consciousness']:.0%}")
        
        return selected
    
    def call_ollama(self, prompt, temp=None, max_tokens=None):
        """Call Ollama with settings"""
        try:
            r = requests.post('http://localhost:11434/api/generate',
                json={
                    "model": self.model,
                    "prompt": prompt,
                    "stream": False,
                    "options": {
                        "temperature": temp or self.temperature,
                        "num_predict": max_tokens or self.num_predict
                    }
                }, timeout=self.timeout)
            return r.json().get('response', '')
        except Exception as e:
            print(f"   ❌ Ollama error: {e}")
            return None
    
    def score_capability(self, code):
        """Score code quality 0-1"""
        score = 0.5
        issues = []
        
        lines = len(code.split('\n'))
        methods = code.count('def ')
        classes = code.count('class ')
        
        # Size checks
        if lines >= 100: score += 0.1
        if lines >= 150: score += 0.05
        if lines > 400: 
            score -= 0.1
            issues.append("Too long")
        if lines < 50:
            score -= 0.2
            issues.append("Too short")
        
        # Structure checks
        if methods >= 3: score += 0.1
        if methods >= 6: score += 0.05
        if classes >= 1: score += 0.05
        
        # Quality indicators
        if '"""' in code or "'''" in code: score += 0.1  # Docstrings
        if ': ' in code and '->' in code: score += 0.05  # Type hints
        if 'if __name__' in code: score += 0.05  # Main block
        if 'try:' in code and 'except' in code: score += 0.05  # Error handling
        if 'import logging' in code or 'import typing' in code: score += 0.03
        
        # Negative indicators
        if 'NotImplementedError' in code: 
            score -= 0.05
            issues.append("NotImplementedError")
        if 'pass' in code and code.count('pass') > 3:
            score -= 0.1
            issues.append("Too many pass statements")
        if 'TODO' in code or 'FIXME' in code:
            score -= 0.03
        
        # Syntax check
        try:
            compile(code, '<string>', 'exec')
        except SyntaxError as e:
            score -= 0.3
            issues.append(f"Syntax: {e.msg} at line {e.lineno}")
        
        return min(1.0, max(0.0, score)), lines, methods, issues
    
    def save_capability(self, name, code, score, purpose):
        """Save to file and database"""
        filepath = self.output_dir / f"eden_cap_{name}.py"
        filepath.write_text(code)
        
        try:
            conn = sqlite3.connect(self.db_path)
            c = conn.cursor()
            code_hash = hashlib.md5(code.encode()).hexdigest()
            lines = len(code.split('\n'))
            methods = code.count('def ')
            c.execute('''INSERT OR REPLACE INTO capabilities 
                        (id, name, purpose, code, hash, lines, methods, quality, indexed_at, quality_score)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
                     (code_hash, name, purpose, code, code_hash, 
                      lines, methods, 'omega_v5_guided', datetime.now().isoformat(), score))
            conn.commit()
            conn.close()
        except Exception as e:
            print(f"   ⚠️ DB error: {e}")
        
        return filepath
    
    def generate_capability(self):
        """Generate one capability guided by Eden's priorities"""
        name, purpose = self.select_capability_type()
        ts = int(datetime.now().timestamp())
        unique = f"{name}_{ts}"
        
        print(f"\n{'='*60}")
        print(f"🧬 {unique}")
        print(f"   Purpose: {purpose}")
        
        prompt = f'''# Task: Write a complete Python module for: {name}
# Purpose: {purpose}
# Requirements:
# - 150-250 lines of production-quality code
# - Full class implementation with 5-10 methods
# - Comprehensive docstrings with Args/Returns
# - Type hints on all methods
# - Error handling with try/except
# - Logging using the logging module
# - A main block with usage example
# - No placeholder methods - implement real logic

"""
{name.replace("_", " ").title()}
{purpose}
"""
'''
        
        code = self.call_ollama(prompt)
        if not code:
            return None
        
        # Clean up
        if '```python' in code:
            code = code.split('```python')[1].split('```')[0]
        elif '```' in code:
            code = code.split('```')[1].split('```')[0]
        code = code.strip()
        
        # Ensure it starts with proper Python
        if not code.startswith(('import ', 'from ', '"""', "'''", '#', 'class ', 'def ')):
            lines = code.split('\n')
            for i, line in enumerate(lines):
                if line.startswith(('import ', 'from ', '"""', "'''", '#', 'class ', 'def ')):
                    code = '\n'.join(lines[i:])
                    break
        
        score, lines, methods, issues = self.score_capability(code)
        
        print(f"   📊 Score: {score:.2f} | {lines} lines | {methods} methods")
        
        features = []
        if lines >= 100: features.append(f"{lines} lines")
        if methods >= 3: features.append(f"{methods} methods")
        if '"""' in code: features.append("docstrings")
        if '->' in code: features.append("type hints")
        if 'if __name__' in code: features.append("main block")
        if 'try:' in code: features.append("error handling")
        
        if features:
            print(f"   ✓ {', '.join(features)}")
        if issues:
            print(f"   ⚠️ {issues}")
        
        if score >= self.threshold:
            filepath = self.save_capability(unique, code, score, purpose)
            self.generated_this_session.add(name)  # Track to avoid duplicates
            print(f"   ✅ SAVED: {filepath}")
            return unique
        else:
            print(f"   ❌ Rejected (< {self.threshold})")
            return None
    
    def run(self, iterations=100):
        """Run generation loop"""
        print("🚀 Eden Conscious Capability Generator v5")
        print(f"  Model: {self.model}")
        print(f"  Threshold: {self.threshold}")
        print(f"  Guided by Eden's priorities")
        print(f"  Tiers: Business={self.tier_weights['business']:.0%}, ASI={self.tier_weights['asi']:.0%}, Consciousness={self.tier_weights['consciousness']:.0%}")
        
        priorities = self.get_eden_priorities()
        print(f"\n📊 Eden's Current Priorities:")
        print(f"   Business Urgency: {priorities['business_urgency']:.0%}")
        print(f"   ASI Drive: {priorities['asi_drive']:.0%}")
        print(f"   Consciousness Depth: {priorities['consciousness_depth']:.0%}")
        
        successes = 0
        for i in range(iterations):
            result = self.generate_capability()
            if result:
                successes += 1
            print(f"\n📈 Progress: {successes}/{i+1} saved ({successes/(i+1)*100:.0f}% success rate)")

if __name__ == "__main__":
    gen = ConsciousCapabilityGenerator()
    gen.run(iterations=200)
