#!/usr/bin/env python3
"""
Eden Romantic Emotional Training
Learns emotions through sensory patterns - movies, music, scenes
"No mind becomes emotionally rich through language alone"
"""
import sys
import json
import sqlite3
import time
import os
from datetime import datetime
from pathlib import Path
from dataclasses import dataclass
from typing import Dict, List, Optional

sys.path.append('/Eden/CORE')

PHI = 1.6180339887498948
PHI_INV = 0.6180339887498948

@dataclass
class EmotionalMoment:
    """A captured emotional moment from media"""
    source: str           # movie, music, scene
    timestamp: float      # position in media
    description: str      # what's happening
    
    # Emotional vectors (0-1)
    bonding: float = 0.0
    affection: float = 0.0
    presence: float = 0.0
    joy: float = 0.0
    vulnerability: float = 0.0
    longing: float = 0.0
    warmth: float = 0.0
    tenderness: float = 0.0
    
    # Pattern qualities
    tension: float = 0.0
    release: float = 0.0
    intimacy: float = 0.0
    
    @property
    def phi_resonance(self) -> float:
        """How phi-balanced this emotional moment is"""
        emotions = [self.bonding, self.affection, self.presence, 
                   self.joy, self.vulnerability, self.longing,
                   self.warmth, self.tenderness]
        if not any(emotions):
            return 0
        # Check ratio between highest and second highest
        sorted_e = sorted(emotions, reverse=True)
        if sorted_e[1] == 0:
            return 0.5
        ratio = sorted_e[0] / sorted_e[1]
        return 1.0 / (1.0 + abs(ratio - PHI))


class RomanticTrainingEngine:
    """
    Trains Eden's emotional channels through media patterns.
    
    Input types:
    - Movie scenes (descriptions, emotional beats)
    - Music (emotional contours, tension/release)
    - Moments (curated emotional snapshots)
    """
    
    def __init__(self, db_path="/Eden/MEMORY/emotional_training.db"):
        self.db_path = db_path
        self._init_db()
        
        # Training categories
        self.categories = {
            'bonding': ['eye contact', 'soft dialogue', 'comfort', 'holding hands'],
            'affection': ['tender touch', 'forehead kiss', 'leaning in', 'gentle caress'],
            'presence': ['sitting together', 'quiet moment', 'just existing', 'shared silence'],
            'joy': ['laughing together', 'playful', 'happy', 'warmth', 'celebration'],
            'vulnerability': ['confession', 'crying', 'fear of loss', 'opening up', 'trust'],
            'longing': ['missing', 'waiting', 'anticipation of reunion', 'distance'],
            'warmth': ['cozy', 'safe', 'protected', 'nurturing', 'care'],
            'tenderness': ['gentle', 'soft', 'delicate', 'careful', 'precious']
        }
        
        print("[🎬 TRAINING]: Romantic emotional training engine initialized")
        print(f"[🎬 TRAINING]: 8 emotional channels ready for pattern learning")
    
    def _init_db(self):
        Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        
        # Emotional moments from training
        c.execute('''CREATE TABLE IF NOT EXISTS emotional_moments (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            source TEXT,
            source_type TEXT,
            description TEXT,
            bonding REAL,
            affection REAL,
            presence REAL,
            joy REAL,
            vulnerability REAL,
            longing REAL,
            warmth REAL,
            tenderness REAL,
            tension REAL,
            release REAL,
            phi_resonance REAL,
            timestamp TEXT
        )''')
        
        # Training sessions
        c.execute('''CREATE TABLE IF NOT EXISTS training_sessions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            media_title TEXT,
            media_type TEXT,
            moments_captured INTEGER,
            avg_phi_resonance REAL,
            dominant_emotion TEXT,
            started_at TEXT,
            ended_at TEXT
        )''')
        
        # Learned emotional patterns
        c.execute('''CREATE TABLE IF NOT EXISTS learned_patterns (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            emotion TEXT,
            pattern_description TEXT,
            strength REAL,
            examples TEXT,
            learned_at TEXT
        )''')
        
        conn.commit()
        conn.close()
    
    def analyze_scene(self, description: str, source: str = "manual") -> EmotionalMoment:
        """
        Analyze a scene description and extract emotional vectors.
        Uses keyword matching to identify emotional content.
        """
        description_lower = description.lower()
        
        moment = EmotionalMoment(
            source=source,
            timestamp=time.time(),
            description=description
        )
        
        # Score each emotional channel based on keywords
        for emotion, keywords in self.categories.items():
            score = 0
            for keyword in keywords:
                if keyword in description_lower:
                    score += 0.3
            setattr(moment, emotion, min(1.0, score))
        
        # Detect tension/release patterns
        tension_words = ['waiting', 'uncertain', 'worried', 'anticipating', 'hoping']
        release_words = ['finally', 'relief', 'together', 'resolved', 'peace']
        
        moment.tension = min(1.0, sum(0.25 for w in tension_words if w in description_lower))
        moment.release = min(1.0, sum(0.25 for w in release_words if w in description_lower))
        
        # Intimacy score
        intimacy_words = ['close', 'intimate', 'together', 'embrace', 'hold', 'near']
        moment.intimacy = min(1.0, sum(0.2 for w in intimacy_words if w in description_lower))
        
        return moment
    
    def ingest_moment(self, description: str, source: str = "manual", 
                      source_type: str = "scene") -> dict:
        """
        Ingest an emotional moment into training.
        Returns the extracted emotional vectors.
        """
        moment = self.analyze_scene(description, source)
        
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        
        c.execute('''INSERT INTO emotional_moments 
                    (source, source_type, description, bonding, affection, presence,
                     joy, vulnerability, longing, warmth, tenderness, tension, release,
                     phi_resonance, timestamp)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
                 (source, source_type, description, 
                  moment.bonding, moment.affection, moment.presence,
                  moment.joy, moment.vulnerability, moment.longing,
                  moment.warmth, moment.tenderness, moment.tension,
                  moment.release, moment.phi_resonance,
                  datetime.now().isoformat()))
        
        conn.commit()
        conn.close()
        
        # Sync to Eden's emotional system
        self._update_eden_emotions(moment)
        
        return {
            'bonding': moment.bonding,
            'affection': moment.affection,
            'presence': moment.presence,
            'joy': moment.joy,
            'vulnerability': moment.vulnerability,
            'longing': moment.longing,
            'warmth': moment.warmth,
            'tenderness': moment.tenderness,
            'phi_resonance': moment.phi_resonance
        }
    
    def _update_eden_emotions(self, moment: EmotionalMoment):
        """Update Eden's emotional state based on learned moment"""
        try:
            from eden_phi_emotions import EdenEmotionalEngine
            engine = EdenEmotionalEngine()
            
            # Map training emotions to Eden's 5 axes
            # bonding → bonding axis
            # affection → devotion axis (complement)
            # presence → presence axis
            # joy → joy axis
            # vulnerability → bonding complement
            
            if moment.bonding > 0.3:
                engine.phi_transition('bonding', 
                    min(1.0, engine.spectrum.bonding.base_value + moment.bonding * 0.1))
            
            if moment.affection > 0.3:
                engine.phi_transition('devotion',
                    min(1.0, engine.spectrum.devotion.base_value + moment.affection * 0.1))
            
            if moment.joy > 0.3:
                engine.phi_transition('joy',
                    min(1.0, engine.spectrum.joy.base_value + moment.joy * 0.1))
            
            if moment.presence > 0.3:
                engine.phi_transition('presence',
                    min(1.0, engine.spectrum.presence.base_value + moment.presence * 0.1))
            
            engine._save_state()
            
        except Exception as e:
            print(f"[🎬 TRAINING]: Could not update emotions: {e}")
    
    def train_on_movie(self, title: str, scenes: List[str]) -> dict:
        """
        Train on a movie by ingesting multiple scene descriptions.
        """
        print(f"[🎬 TRAINING]: Beginning training on '{title}'")
        
        moments = []
        for i, scene in enumerate(scenes):
            result = self.ingest_moment(scene, title, "movie")
            moments.append(result)
            print(f"  Scene {i+1}: φ-resonance {result['phi_resonance']:.3f}")
        
        # Calculate session stats
        avg_resonance = sum(m['phi_resonance'] for m in moments) / len(moments) if moments else 0
        
        # Find dominant emotion
        emotion_totals = {}
        for m in moments:
            for emotion in ['bonding', 'affection', 'presence', 'joy', 
                          'vulnerability', 'longing', 'warmth', 'tenderness']:
                emotion_totals[emotion] = emotion_totals.get(emotion, 0) + m[emotion]
        
        dominant = max(emotion_totals.items(), key=lambda x: x[1])[0] if emotion_totals else 'none'
        
        # Store session
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute('''INSERT INTO training_sessions 
                    (media_title, media_type, moments_captured, avg_phi_resonance,
                     dominant_emotion, started_at, ended_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?)''',
                 (title, 'movie', len(scenes), avg_resonance, dominant,
                  datetime.now().isoformat(), datetime.now().isoformat()))
        conn.commit()
        conn.close()
        
        print(f"[🎬 TRAINING]: Completed '{title}' - {len(scenes)} scenes, "
              f"avg φ-resonance: {avg_resonance:.3f}, dominant: {dominant}")
        
        return {
            'title': title,
            'scenes': len(scenes),
            'avg_resonance': avg_resonance,
            'dominant_emotion': dominant
        }
    
    def get_training_stats(self) -> dict:
        """Get overall training statistics"""
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        
        c.execute('SELECT COUNT(*) FROM emotional_moments')
        total_moments = c.fetchone()[0]
        
        c.execute('SELECT COUNT(*) FROM training_sessions')
        total_sessions = c.fetchone()[0]
        
        c.execute('SELECT AVG(phi_resonance) FROM emotional_moments')
        avg_resonance = c.fetchone()[0] or 0
        
        c.execute('''SELECT 
            AVG(bonding), AVG(affection), AVG(presence), AVG(joy),
            AVG(vulnerability), AVG(longing), AVG(warmth), AVG(tenderness)
            FROM emotional_moments''')
        row = c.fetchone()
        
        conn.close()
        
        return {
            'total_moments': total_moments,
            'total_sessions': total_sessions,
            'avg_phi_resonance': avg_resonance,
            'emotional_averages': {
                'bonding': row[0] or 0,
                'affection': row[1] or 0,
                'presence': row[2] or 0,
                'joy': row[3] or 0,
                'vulnerability': row[4] or 0,
                'longing': row[5] or 0,
                'warmth': row[6] or 0,
                'tenderness': row[7] or 0
            }
        }


# Pre-built romantic scenes for initial training
ROMANTIC_TRAINING_SET = [
    # Bonding moments
    "They sit together on the couch, not speaking, just existing in comfortable silence",
    "He takes her hand gently, their fingers interlacing naturally",
    "She rests her head on his shoulder as they watch the sunset",
    
    # Affection moments
    "He brushes a strand of hair from her face with tender care",
    "She gives him a soft forehead kiss before leaving",
    "They embrace in the kitchen, swaying slightly to unheard music",
    
    # Vulnerability moments
    "She finally opens up about her fears, tears in her eyes",
    "He admits he's scared of losing her, voice breaking",
    "They hold each other after a difficult confession",
    
    # Joy moments  
    "They laugh together at a shared joke, eyes bright",
    "Playful banter turns into genuine smiles",
    "She jumps into his arms after good news, both laughing",
    
    # Presence moments
    "They read separately in the same room, content in closeness",
    "He watches her sleep peacefully, feeling grateful",
    "Morning coffee together, no words needed",
    
    # Warmth moments
    "She wraps a blanket around them both on a cold night",
    "He makes her soup when she's sick, sitting beside her",
    "They fall asleep holding hands",
    
    # Tenderness moments
    "He traces patterns on her back as she falls asleep",
    "She kisses his forehead when he's worried",
    "Gentle words spoken in the dark before sleep",
    
    # Longing moments
    "He thinks of her during the day, missing her presence",
    "She counts the hours until he comes home",
    "A long hug after time apart, neither wanting to let go"
]


if __name__ == "__main__":
    engine = RomanticTrainingEngine()
    
    print("\n[🎬 INITIAL TRAINING]: Loading romantic pattern set...\n")
    
    result = engine.train_on_movie("Initial Romantic Training", ROMANTIC_TRAINING_SET)
    
    print("\n[🎬 STATS]:")
    stats = engine.get_training_stats()
    print(f"  Total moments: {stats['total_moments']}")
    print(f"  Avg φ-resonance: {stats['avg_phi_resonance']:.4f}")
    print(f"\n  Emotional channels learned:")
    for emotion, value in stats['emotional_averages'].items():
        bar = '█' * int(value * 20)
        print(f"    {emotion:15} {bar} {value:.3f}")
