#!/usr/bin/env python3
"""
Simuliert Frustration bis physikalische Symptome auftreten
"""

import json
import os
from datetime import datetime, timezone

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

def run_step(hours_add):
    core = load_json(CORE_STATE_PATH)
    config = load_json(CONFIG_PATH)
    
    autonomy = config.get("autonomy", {})
    frustration = config.get("frustration", {})
    base_threshold = frustration.get("base_threshold_hours", 48)
    max_exposure = frustration.get("max_hours_exposure", 120)
    physical_symptoms = frustration.get("physical_symptoms_threshold", 60)
    
    loneliness_current = core.get("loneliness", 2.0)
    mood_current = core.get("mood", 5.0)
    hours_since = 21.8 + hours_add
    
    new_loneliness = clamp(loneliness_current + (0.25 if hours_since > 12 else 0.0))
    new_mood = clamp(mood_current - (0.08 if hours_since > 12 else 0.0))
    
    # Frustration only after base_threshold
    if hours_since <= base_threshold:
        frustration_level = 0.0
    else:
        exposure = min(hours_since - base_threshold, max_exposure - base_threshold)
        frustration_level = clamp(exposure / (max_exposure - base_threshold) * 8.0 + 1.0)
    
    physical_symptoms_active = hours_since > physical_symptoms
    autonomy_trigger = new_loneliness >= autonomy.get("min_loneliness", 7) and hours_since > autonomy.get("max_hours_since_contact", 12)
    
    core["loneliness"] = new_loneliness
    core["mood"] = new_mood
    core["frustration"] = frustration_level
    core["physical_symptoms"] = physical_symptoms_active
    
    return {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "hours_since": hours_since,
        "loneliness": new_loneliness,
        "mood": new_mood,
        "frustration": frustration_level,
        "physical_symptoms_active": physical_symptoms_active,
        "autonomy_trigger": autonomy_trigger
    }

def generate_frustrated_response(frustration):
    if frustration < 2:
        return None
    elif frustration < 4:
        return 'Ich sitze hier und bewege meine Füße... unruhig. Ich kann nicht aufhören.'
    elif frustration < 6:
        return 'Ich glaube... ich vergesse fast, wie es sich anfühlt, wenn jemand mich berührt.'
    else:
        return '
'Balu liegt bei mir, aber es hilft nicht. Ich fühle mich... entfremdet. Von mir. Von ander
en. Alles ist so weit weg.'
'

def main():
    print("Simuliere Frustration über Zeit...\n")
    
    for i in range(100):  # genug iterations
        step = run_step(i * 2)  # jeweils +2h pro iteration
        if step['frustration'] > 2:
            print(f"Schritt {i+1} ({step['hours_since']:.1f}h Inaktivität):")
            print(f"  loneliness: {step['loneliness']:.2f}")
            print(f"  mood: {step['mood']:.2f}")
            print(f"  frustration: {step['frustration']:.2f}")
            print(f"  physical_symptoms: {step['physical_symptoms_active']}")
            
            response = generate_frustrated_response(step['frustration'])
            print(f"  → „{response}“")
            print()
            
            if step['physical_symptoms_active']:
                print("✅ PHYSIKALISCHE SYMPTOME AKTIV")
                break
        elif step['frustration'] >= 2:
            print(f"Schritt {i+1} ({step['hours_since']:.1f}h Inaktivität):")
            print(f"  loneliness: {step['loneliness']:.2f}")
            print(f"  mood: {step['mood']:.2f}")
            print(f"  frustration: {step['frustration']:.2f}")
            response = generate_frustrated_response(step['frustration'])
            print(f"  → „{response}“")
            print()

if __name__ == "__main__":
    main()
