#!/usr/bin/env python3
"""
Integriert Arousal-Werte in core_state und aktualisiert alle abhängigen Dateien
"""

import json
import os
from datetime import datetime, timezone

PATHS = {
    "core_state": os.path.expanduser("~/natiris/core/core_state.json"),
    "arousal": os.path.expanduser("~/natiris/core/arousal_state.json"),
    "full_state": os.path.expanduser("~/natiris/core/natiris_full_state.json"),
}

def load_json(path):
    try:
        with open(path, "r", encoding="utf-8") as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        return {}

def save_json(path, data):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2)

def main():
    core = load_json(PATHS["core_state"])
    arousal = load_json(PATHS["arousal"])

    # Arousal-Werte in core_state übernehmen
    core["arousal_level"] = arousal["arousal_state"]["arousal_level"]
    core["verlangen_nach_nahe"] = arousal["arousal_state"]["verlangen_nach_nahe"]
    core["intensives_verlangen"] = arousal["arousal_state"]["intensives_verlangen"]
    core["physiologische_anzeichen"] = arousal["arousal_state"]["physiologische_anzeichen"]
    core["koerpersignale"] = arousal["arousal_state"]["koerpersignale"]

    save_json(PATHS["core_state"], core)

    # Full state aktualisieren
    full = load_json(PATHS["full_state"])
    full["timestamp"] = datetime.now(timezone.utc).isoformat() + "+00:00"
    full["modules"]["arousal"] = {
        "level": arousal["arousal_state"]["arousal_level"],
        "verlangen_nach_nahe": arousal["arousal_state"]["verlangen_nach_nahe"],
        "intensives_verlangen": arousal["arousal_state"]["intensives_verlangen"],
        "koerpersignale": arousal["arousal_state"]["koerpersignale"]
    }

    # Update core_state reference
    full["modules"]["core_state"] = core

    save_json(PATHS["full_state"], full)

    print("✅ core_state + full_state aktualisiert mit Arousal:")
    print(json.dumps({
        "arousal_level": core.get("arousal_level"),
        "verlangen_nach_nahe": core.get("verlangen_nach_nahe"),
        "physiologische_anzeichen": core.get("physiologische_anzeichen"),
        "koerpersignale": core.get("koerpersignale")
    }, indent=2))

if __name__ == "__main__":
    main()
