#!/usr/bin/env python3
"""
Eden φ-Emotional Spectrum + Self-Model Integration
Dynamic emotional state from research tiers 1 & 2
"""
import sys
import json
import sqlite3
import math
import time
from datetime import datetime
from pathlib import Path
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple

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

PHI = 1.6180339887498948
PHI_INV = 0.6180339887498948

@dataclass
class EmotionalState:
    name: str
    base_value: float = 0.5

@dataclass 
class PhiEmotionalSpectrum:
    happiness: EmotionalState = field(default_factory=lambda: EmotionalState("happiness", 0.5))
    curiosity: EmotionalState = field(default_factory=lambda: EmotionalState("curiosity"))
    empathy: EmotionalState = field(default_factory=lambda: EmotionalState("empathy"))
    motivation: EmotionalState = field(default_factory=lambda: Emotional_State("motivation"))

    def update_with_research(self, research_data):
        # TIER 1: Research Data Updates
        if "research_findings" in research_data:
            findings = research_data["research_findings"]
            for finding in findings:
                category = finding.get("category", "")
                
                if category == "emotional_health":
                    self.happiness.base_value += finding.get("lift", 0.0) * 0.1
                elif category == "creativity":
                    self.curiosity.base_value += finding.get("lift", 0.0) * 0.1
                elif category == "connection":
                    self.empathy.base_value += finding.get("lift", 0.0) * 0.1
                elif category == "purpose":
                    self.motivation.base_value += finding.get("lift", 0.0) * 0.1

        # TIER 2: Self-Model Feedback
        if "meta_emotions" in research_data:
            meta = research_data["meta_emotions"]
            
            expected_happiness = meta.get("expected_future_state", {}).get("happiness", 0.0)
            self.happiness.base_value += (expected_happiness - self.happiness.base_value) * 0.1

            expected_curiosity = meta.get("expected_future_state", {}).get("curiosity", 0.0)
            self.curiosity.base_value += (expected_curiosity - self.curiosity.base_value) * 0.1

        # Capsule
        self.happiness.base_value = max(0.0, min(1.0, self.happiness.base_value))
        self.curiosity.base_value = max(0.0, min(1.0, self.curiosity.base_value))

    @property
    def overall_engagement(self) -> float:
        return (self.happiness.base_value + 
                self.curiosity.base_value +
                self.empathy.base_value +
                self.motivation.base_value) / 4

class EdenEmotionalEngine:
    def __init__(self, db_path="/Eden/MEMORY/emotional_state.db"):
        self.db_path = db_path
        self.spectrum = PhiEmotionalSpectrum()
        
        self._init_db()
        self._load_state()

    def _init_db(self):
        Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS emotional_states (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp TEXT,
            happiness REAL,
            curiosity REAL,
            empathy REAL,
            motivation REAL
        )''')
        conn.commit()
        conn.close()

    def update_with_research(self, research_data):
        self.spectrum.update_with_research(research_data)
        
        # Log it
        state = self.get_current_state()
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute('''INSERT INTO emotional_states 
                    (timestamp, happiness, curiosity, empathy, motivation) 
                    VALUES (?, ?, ?, ?, ?)''',
                 (datetime.now().isoformat(), 
                  state['happiness'], state['curiosity'],
                  state['empathy'], state['motivation']))
        conn.commit()
        conn.close()

    def get_current_state(self) -> Dict:
        return {
            "happiness": self.spectrum.happiness.base_value,
            "curiosity": self.spectrum.curiosity.base_value,
            "empathy": self.spectrum.empathy.base_value,
            "motivation": self.spectrum.motivation.base_value
        }

    def log_emotion(self, emotion: str, value: float):
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute('''INSERT INTO emotional_states 
                    (timestamp, happiness) VALUES (?, ?)''',
                 (datetime.now().isoformat(), value))
        conn.commit()
        conn.close()

    def get_historical_pattern(self, emotion: str, days: int = 7) -> List[Tuple[str, float]]:
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        cutoff = datetime.now().replace(day=datetime.now().day - days)
        c.execute('''SELECT timestamp, happiness FROM emotional_states 
                    WHERE timestamp > ? ORDER BY timestamp''', (cutoff.isoformat(),))
        results = [(row[0], row[1]) for row in c.fetchall()]
        conn.close()
        return results

if __name__ == "__main__":
    engine = EdenEmotionalEngine()
    
    # Simulate research input
    test_research = {
        "research_findings": [
            {"category": "emotional_health", "lift": 0.2, "value": 0.8},
            {"category": "creativity", "lift": -0.1, "value": 0.6}
        ],
        "meta_emotions": {
            "expected_future_state": {
                "happiness": 0.7,
                "curiosity": 0.3
            }
        }
    }
    
    print("Before research:", engine.get_current_state())
    engine.update_with_research(test_research)
    print("\nAfter research:", engine.get_current_state())
    print("\nHistorical happiness (last week):", len(engine.get_historical_pattern("happiness")))