#!/usr/bin/env python3
"""
Simuliert fortlaufende Inaktivität bis Autonomie-Trigger auslöst
"""

import json
import os
from datetime import datetime, timezone

CORE_STATE_PATH = os.path.expanduser("~/natiris/core/core_state.json")
INNER_LIFE_PATH = os.path.expanduser("~/natiris/core/inner_life_log.json")
CONFIG_PATH = os.path.expanduser("~/natiris/config/character_genesis.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 clamp(val, lo=0.0, hi=10.0):
    return max(lo, min(hi, float(val)))

def run_step(hours_add):
    """Simuliert eine Zeitspanne hours_add Stunden Inaktivität"""
    core = load_json(CORE_STATE_PATH)
    config = load_json(CONFIG_PATH)
    old_inner = load_json(INNER_LIFE_PATH)
    
    autonomy = config.get("autonomy", {})
    loneliness_threshold = autonomy.get("min_loneliness", 7)
    max_hours = autonomy.get("max_hours_since_contact", 12)
    
    # Neue Werte berechnen
    loneliness_current = core.get("loneliness", 2.0)
    mood_current = core.get("mood", 5.0)
    
    new_loneliness = clamp(loneliness_current + (hours_add * 0.25))  # ~0.25 pro Stunde
    new_mood = clamp(mood_current - (hours_add * 0.08))  # ~0.08 pro Stunde
    
    hours_since = old_inner["hours_since_last_contact"] + hours_add
    autonomy_trigger = new_loneliness >= loneliness_threshold and hours_since > max_hours
    
    log = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "old": {
            "loneliness": loneliness_current,
            "mood": mood_current
        },
        "new": {
            "loneliness": new_loneliness,
            "mood": new_mood
        },
        "autonomy_trigger": autonomy_trigger,
        "hours_since_last_contact": round(hours_since, 2),
        "delta_hours": hours_add
    }
    
    save_json(INNER_LIFE_PATH, log)
    
    core["loneliness"] = new_loneliness
    core["mood"] = new_mood
    save_json(CORE_STATE_PATH, core)
    
    return log

def main():
    print("Simuliere Inaktivität bis Autonomie-Trigger...\n")
    
    for i in range(1, 10):
        log = run_step(2)  # jeweils 2 Stunden dazu
        print(f"Schritt {i}:")
        print(f"  hours_since: {log['hours_since_last_contact']:.2f}h")
        print(f"  loneliness: {log['new']['loneliness']:.2f}")
        print(f"  mood: {log['new']['mood']:.2f}")
        print(f"  autonomy_trigger: {log['autonomy_trigger']}")
        print()
        
        if log["autonomy_trigger"]:
            print("✅ AUTONOMIE-TRIGGER AUSGELÖST!")
            break

if __name__ == "__main__":
    main()
