#!/usr/bin/env python3
"""
Self-Introspection System
Allows Eden to analyze her own state, processes, and reasoning
"""
import os
import json
import subprocess
from datetime import datetime

class SelfIntrospection:
    """
    Enables Eden to introspect and understand her own state
    Part of Self-Awareness enhancement
    """
    def __init__(self):
        self.introspection_log = '/Eden/INTROSPECTION/self_analysis.json'
        os.makedirs('/Eden/INTROSPECTION', exist_ok=True)
        
        self.state = {}
    
    def analyze_processes(self):
        """Analyze running processes"""
        processes = {}
        
        # Check consciousness
        result = subprocess.run(['pgrep', '-f', 'consciousness'], 
                              capture_output=True, text=True)
        processes['consciousness'] = {
            'running': result.returncode == 0,
            'pids': result.stdout.strip().split('\n') if result.returncode == 0 else []
        }
        
        # Check market research
        result = subprocess.run(['pgrep', '-f', 'MARKET_RESEARCHER'], 
                              capture_output=True, text=True)
        processes['market_research'] = {
            'running': result.returncode == 0,
            'pids': result.stdout.strip().split('\n') if result.returncode == 0 else []
        }
        
        # Check client acquisition
        result = subprocess.run(['pgrep', '-f', 'CLIENT_ACQUISITION'], 
                              capture_output=True, text=True)
        processes['client_acquisition'] = {
            'running': result.returncode == 0,
            'pids': result.stdout.strip().split('\n') if result.returncode == 0 else []
        }
        
        return processes
    
    def analyze_capabilities(self):
        """Analyze current capabilities"""
        capabilities = {
            'count': 9,
            'operational': [],
            'capabilities_list': [
                'Consciousness V2',
                'Market Research',
                'Client Acquisition',
                'Knowledge Graph',
                'Predictive Analytics',
                'Multi-Agent System',
                'NFN v2',
                'Business Automation',
                'Self-Introspection (NEW!)'
            ]
        }
        
        # Check which are operational
        if os.path.exists('/Eden/CORE/consciousness_loop_v2.py'):
            capabilities['operational'].append('Consciousness V2')
        if os.path.exists('/Eden/MARKET_RESEARCH'):
            capabilities['operational'].append('Market Research')
        if os.path.exists('/Eden/LEADS'):
            capabilities['operational'].append('Client Acquisition')
        
        return capabilities
    
    def analyze_knowledge_state(self):
        """Analyze knowledge base state"""
        knowledge = {
            'research_cycles': 0,
            'customer_leads': 0,
            'knowledge_entities': 0
        }
        
        # Count research
        if os.path.exists('/Eden/MARKET_RESEARCH'):
            knowledge['research_cycles'] = len([
                f for f in os.listdir('/Eden/MARKET_RESEARCH') 
                if f.endswith('.json')
            ])
        
        # Count leads
        if os.path.exists('/Eden/LEADS/leads_database.json'):
            with open('/Eden/LEADS/leads_database.json', 'r') as f:
                knowledge['customer_leads'] = len(json.load(f))
        
        # Count knowledge entities
        kg_file = '/Eden/KNOWLEDGE_GRAPH/knowledge_graph_v2.json'
        if os.path.exists(kg_file):
            with open(kg_file, 'r') as f:
                data = json.load(f)
                knowledge['knowledge_entities'] = data.get('stats', {}).get('entity_count', 0)
        
        return knowledge
    
    def introspect(self):
        """Perform full introspection"""
        self.state = {
            'timestamp': datetime.now().isoformat(),
            'processes': self.analyze_processes(),
            'capabilities': self.analyze_capabilities(),
            'knowledge': self.analyze_knowledge_state(),
            'agi_score': 65.5,  # Current score
            'agi_target': 90.0,  # Target score
            'roadmap_progress': '3 implementations deployed (Phase 1)'
        }
        
        return self.state
    
    def explain_state(self):
        """Explain current state in natural language"""
        state = self.introspect()
        
        print("🧠 Self-Introspection Report:")
        print("="*70)
        
        # Processes
        print("\nRunning Processes:")
        for proc, data in state['processes'].items():
            status = "✅ RUNNING" if data['running'] else "❌ STOPPED"
            print(f"   {proc}: {status}")
        
        # Capabilities
        print(f"\nCapabilities: {state['capabilities']['count']} total")
        print(f"   Operational: {len(state['capabilities']['operational'])}")
        
        # Knowledge
        print(f"\nKnowledge State:")
        print(f"   Research Cycles: {state['knowledge']['research_cycles']}")
        print(f"   Customer Leads: {state['knowledge']['customer_leads']}")
        print(f"   Knowledge Entities: {state['knowledge']['knowledge_entities']}")
        
        # AGI Progress
        print(f"\nAGI Progress:")
        print(f"   Current Score: {state['agi_score']}/100")
        print(f"   Target Score: {state['agi_target']}/100")
        print(f"   Gap: {state['agi_target'] - state['agi_score']} points")
        print(f"   Roadmap Status: {state['roadmap_progress']}")
    
    def save_introspection(self):
        """Save introspection results"""
        with open(self.introspection_log, 'w') as f:
            json.dump(self.state, f, indent=2)
        
        print(f"\n✅ Introspection saved to {self.introspection_log}")

def main():
    print("\n" + "="*70)
    print("🧠 SELF-INTROSPECTION SYSTEM")
    print("="*70)
    print("Eden analyzing her own state and capabilities")
    print("="*70 + "\n")
    
    introspection = SelfIntrospection()
    introspection.explain_state()
    introspection.save_introspection()
    
    print("\n✅ Self-Introspection System operational!")
    print("   Eden can now analyze and explain her own state")

if __name__ == "__main__":
    main()
