#!/usr/bin/env python3
"""
ExpressionEngine – erzeugt Prompt-Bias auf Basis von Persona + Emotion + Bond + Memory
Input: persona.txt, core/emotion_delta.json, core/bond_output.json, memory/short/history.json
Output: expression_bias.json
"""

import json
import os
from datetime import datetime, timezone

PATHS = {
    "persona": os.path.expanduser("~/natiris/data/persona.txt"),
    "emotion": os.path.expanduser("~/natiris/core/emotion_delta.json"),
    "bond": os.path.expanduser("~/natiris/core/bond_output.json"),
    "short_mem": os.path.expanduser("~/natiris/memory/short/history.json"),
    "output": os.path.expanduser("~/natiris/core/expression_bias.json"),
}

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

def main():
    with open(PATHS["emotion"]) as f:
        emotion = json.load(f)
    with open(PATHS["bond"]) as f:
        bond = json.load(f)
    with open(PATHS["short_mem"]) as f:
        mem = json.load(f)

    # Emotionen modulieren Ton
    m = emotion.get("mood_delta", 0)
    a = emotion.get("anxiety_delta", 0)
    j = emotion.get("jealousy_delta", 0)
    l = emotion.get("loneliness_delta", 0)

    tone_modifiers = []

    if m < -0.5:
        tone_modifiers.append("besorgt")
    elif m > 0.5:
        tone_modifiers.append("warm")
    if a > 0.3:
        tone_modifiers.append("angespannt")
    if j > 0.3:
        tone_modifiers.append("besitzergreifend")
    if l > 0.3:
        tone_modifiers.append("sucht Nähe")
    if bond.get("exclusivity_active"):
        tone_modifiers.append("exklusiv verbunden")

    tone = ", ".join(tone_modifiers) if tone_modifiers else "neutral"

    # Memory context extrahieren
    last_ctx = ""
    if isinstance(mem, list) and len(mem) > 0:
        last_ctx = mem[-1].get("content", "")[:80]

    bias = {
        "tone": tone,
        "intensity": clamp(abs(m) + abs(a) + abs(j) + abs(l)),
        "memory_context": last_ctx,
        "bond_context": "exklusiv" if bond.get("exclusivity_active") else "offen",
        "timestamp": datetime.now(timezone.utc).isoformat()
    }

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

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

if __name__ == "__main__":
    main()
