#!/usr/bin/env python3
"""
EmotionEngine – berechnet Emotionen basierend auf core_state, user_state, events
Input: core_state.json, user_state.json, events.json
Output: emotion_delta.json
"""

import json
import os

PATHS = {
    "core_state": os.path.expanduser("~/natiris/core/core_state.json"),
    "user_state": lambda u: os.path.expanduser(f"~/natiris/core/users/{u}.json"),
    "events": os.path.expanduser("~/natiris/memory/short/history.json"),
    "output": os.path.expanduser("~/natiris/core/emotion_delta.json"),
}

def clamp(val, lo=0.0, hi=10.0):
    return max(lo, min(hi, float(val)))

def compute_emotion_delta(core, user, events):
    mood = core.get("mood", 5.0)
    loneliness = core.get("loneliness", 2.0)
    anxiety = core.get("anxiety", 1.0)

    sentiment = user.get("sentiment", "neutral")
    interaction_count = user.get("interaction_count", 0)

    msg_count = len(events)
    positive_msgs = sum(1 for e in events if e.get("sentiment") == "positive")

    mood_delta = clamp((positive_msgs - msg_count * 0.2) * 0.5 + (0.3 if sentiment == "positive" else -0.3))

    loneliness_delta = clamp(-(interaction_count * 0.03) + (0.2 if loneliness > 7 else -0.1))

    anxiety_delta = clamp(loneliness * 0.05 - mood * 0.02 + (0.2 if msg_count == 0 else -0.1))

    jealousy_delta = clamp(-0.1 if core.get("bonded_to") is None else 0.0)

    return {
        "mood_delta": mood_delta,
        "loneliness_delta": loneliness_delta,
        "anxiety_delta": anxiety_delta,
        "jealousy_delta": jealousy_delta
    }

def main():
    with open(PATHS["core_state"]) as f:
        core = json.load(f)

    # user_state laden (default user)
    user_path = PATHS["user_state"]("user1")
    if os.path.exists(user_path):
        with open(user_path) as f:
            user = json.load(f)
    else:
        user = {"interaction_count": 0, "sentiment": "neutral"}

    with open(PATHS["events"]) as f:
        events = json.load(f)

    delta = compute_emotion_delta(core, user, events)

    with open(PATHS["output"], "w") as f:
        json.dump(delta, f, indent=2)

    print(json.dumps(delta, indent=2))

if __name__ == "__main__":
    main()
