#!/usr/bin/env python3
"""
Continuous Learning Monitor
Tracks Eden's knowledge growth and learning progress
"""
import os
import json
import time
from datetime import datetime, timedelta

class ContinuousLearningMonitor:
    """
    Monitors Eden's continuous learning across all systems
    Part of Knowledge & Understanding enhancement
    """
    def __init__(self):
        self.metrics_file = '/Eden/METRICS/learning_progress.json'
        os.makedirs('/Eden/METRICS', exist_ok=True)
        
        self.baseline = self.establish_baseline()
        self.current = {}
    
    def establish_baseline(self):
        """Establish learning baseline"""
        baseline = {
            'timestamp': datetime.now().isoformat(),
            'research_cycles': self.count_research_cycles(),
            'customer_leads': self.count_leads(),
            'knowledge_entities': self.count_knowledge_entities(),
            'capabilities': 9,
            'agi_score': 65.5
        }
        
        print("📊 Learning Baseline Established:")
        for key, value in baseline.items():
            if key != 'timestamp':
                print(f"   {key}: {value}")
        
        return baseline
    
    def count_research_cycles(self):
        """Count total research cycles"""
        if os.path.exists('/Eden/MARKET_RESEARCH'):
            return len([f for f in os.listdir('/Eden/MARKET_RESEARCH') 
                       if f.endswith('.json')])
        return 0
    
    def count_leads(self):
        """Count customer leads"""
        if os.path.exists('/Eden/LEADS/leads_database.json'):
            with open('/Eden/LEADS/leads_database.json', 'r') as f:
                return len(json.load(f))
        return 0
    
    def count_knowledge_entities(self):
        """Count knowledge graph 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)
                return data.get('stats', {}).get('entity_count', 0)
        return 0
    
    def measure_current_state(self):
        """Measure current learning state"""
        self.current = {
            'timestamp': datetime.now().isoformat(),
            'research_cycles': self.count_research_cycles(),
            'customer_leads': self.count_leads(),
            'knowledge_entities': self.count_knowledge_entities(),
            'capabilities': 9,  # Will update as we add more
            'agi_score': 65.5  # Will update with improvements
        }
        return self.current
    
    def calculate_growth(self):
        """Calculate learning growth since baseline"""
        current = self.measure_current_state()
        
        growth = {}
        for key in self.baseline:
            if key != 'timestamp' and isinstance(self.baseline[key], (int, float)):
                baseline_val = self.baseline[key]
                current_val = current[key]
                
                if baseline_val > 0:
                    growth[key] = {
                        'absolute': current_val - baseline_val,
                        'percent': ((current_val - baseline_val) / baseline_val) * 100
                    }
                else:
                    growth[key] = {
                        'absolute': current_val,
                        'percent': 100.0 if current_val > 0 else 0
                    }
        
        return growth
    
    def save_metrics(self):
        """Save learning metrics"""
        metrics = {
            'baseline': self.baseline,
            'current': self.current,
            'growth': self.calculate_growth(),
            'last_updated': datetime.now().isoformat()
        }
        
        with open(self.metrics_file, 'w') as f:
            json.dump(metrics, f, indent=2)
        
        print(f"\n✅ Metrics saved to {self.metrics_file}")
    
    def show_progress(self):
        """Display learning progress"""
        growth = self.calculate_growth()
        
        print("\n📈 Learning Progress:")
        for metric, data in growth.items():
            print(f"   {metric}:")
            print(f"      Growth: +{data['absolute']} ({data['percent']:+.1f}%)")

def main():
    print("\n" + "="*70)
    print("📊 CONTINUOUS LEARNING MONITOR")
    print("="*70)
    print("Tracking Eden's knowledge growth in real-time")
    print("="*70 + "\n")
    
    monitor = ContinuousLearningMonitor()
    monitor.show_progress()
    monitor.save_metrics()
    
    print("\n✅ Continuous Learning Monitor operational!")
    print("   Tracking: Research, Customers, Knowledge, AGI Score")

if __name__ == "__main__":
    main()
