import json
from pathlib import Path
from datetime import datetime

class SelfLearningEngine:
    """
    Genesis Phase 3: Autonomous Learning Engine.
    Analyzes session logs and memories to extract PATTERNS and LESSONS.
    """
    def __init__(self, kernel):
        self.kernel = kernel
        self.rlm = kernel.rlm

    def synthesize_session(self, session_data):
        """Extract higher-order knowledge from a finished session."""
        print(f"🔬 [LEARNER] Synthesizing Session {session_data['session_id']}...")
        
        # 1. Lesson Extraction (from errors/solutions)
        if session_data.get("surprises") > 0:
            self.rlm.store(
                name=f"LESSON_{session_data['session_id']}",
                entity_type="LESSON",
                observations=[
                    "Analyzed high-surprise events from session.",
                    f"Detected intents: {', '.join(session_data['intents'])}"
                ]
            )

        # 2. Pattern Recognition
        # (Conceptual: Find repeated intents or tool usages)
        common_intents = [i for i in session_data['intents'] if session_data['intents'].count(i) > 2]
        if common_intents:
            for intent in set(common_intents):
                self.rlm.store(
                    name=f"PATTERN_{intent.upper()}",
                    entity_type="PATTERN",
                    observations=[
                        f"Repeated usage detected in session {session_data['session_id']}",
                        f"Refined intent: {intent}"
                    ]
                )
        
        return True
