#!/usr/bin/env python3
"""
Streamlit WebUI für Natiris – Natürliche, authentische Kommunikation
"""

import streamlit as st
import sys
import os
import json

sys.path.insert(0, os.path.expanduser("~/natiris/core"))

# Engine importieren - MIT LOGGING
import traceback
engine_loaded = False
engine_error = None

try:
    from NaturalLanguageEngine import generate_response, load_json, PATHS
    engine_loaded = True
    print("✅ NaturalLanguageEngine erfolgreich geladen")
except Exception as e:
    engine_error = str(e)
    traceback.print_exc()
    print(f"❌ Fehler beim Laden: {e}")
    
    # Fallback nur wenn nötig
    def generate_response(user_input, state):
        trust = state.get("trust", 5)
        if trust <= 3:
            return random.choice(["...", "Was?", "Nicht deine Sache."])
        elif trust <= 6:
            return random.choice(["Okay.", "Vielleicht.", "Ich weiß nicht."])
        elif trust <= 8:
            return random.choice(["Ich bin hier.", "Erzähl mir mehr.", "Ich höre zu."])
        else:
            return random.choice(["Da bist du ja.", "Ich habe auf dich gewartet.", "Endlich."])
    
    def load_json(path):
        try:
            with open(path) as f:
                return json.load(f)
        except:
            return {}
    
    PATHS = {"state": os.path.expanduser("~/natiris/core/core_state.json")}

import random

st.set_page_config(
    page_title="Natiris", 
    page_icon="🌙", 
    layout="centered",
    initial_sidebar_state="collapsed"
)

# Custom CSS
st.markdown("""
<style>
    .stTextInput>div>div>input {
        border-radius: 20px;
        border: 2px solid #e0e0e0;
        padding: 10px 20px;
    }
    .stButton>button {
        border-radius: 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        padding: 10px 24px;
    }
</style>
""", unsafe_allow_html=True)

# Header
st.title("🌙 Natiris")
st.caption("Authentisch. Vertraut. Echt.")

# Engine-Status anzeigen
if engine_loaded:
    st.sidebar.success("✅ Engine geladen")
else:
    st.sidebar.error(f"❌ Engine nicht geladen: {engine_error}")
    st.sidebar.info("Verwende Fallback-Modus")

# State-Initialisierung
if 'messages' not in st.session_state:
    st.session_state.messages = []

if 'trust_level' not in st.session_state:
    st.session_state.trust_level = 7.0

# Sidebar mit Status
with st.sidebar:
    st.header("Status")
    trust = st.session_state.trust_level
    st.metric("Trust", f"{trust:.1f}/10")
    
    if trust <= 3:
        st.error("Distanziert/Fremd")
    elif trust <= 6:
        st.warning("Vorsichtig/Testend")
    elif trust <= 8:
        st.info("Warm/Gebunden")
    else:
        st.success("Seelenpartner/Exklusiv")

# Chat-Verlauf
for msg in st.session_state.messages:
    if msg["role"] == "user":
        st.markdown(f"**👤 Du:** {msg['content']}")
    else:
        st.markdown(f"**🌙 Natiris:** {msg['content']}")

# Eingabe
st.divider()

with st.form("chat_form", clear_on_submit=True):
    prompt = st.text_input("Nachricht", placeholder="Schreib etwas...", label_visibility="collapsed")
    submitted = st.form_submit_button("Senden")
    
    if submitted and prompt:
        # User-Nachricht
        st.session_state.messages.append({"role": "user", "content": prompt})
        
        # State vorbereiten
        state = {
            "trust": st.session_state.trust_level,
            "mood": 5,
            "loneliness": 4,
            "anxiety": max(0, 10-st.session_state.trust_level),
            "arousal_level": 2,
            "bonded_to": "user_primary"
        }
        
        # Response generieren MIT DEBUG
        try:
            response = generate_response(prompt, state)
            print(f"[DEBUG] Input: {prompt} | Trust: {state['trust']} | Response: {response}")
        except Exception as e:
            response = f"[Fehler: {e}]"
            print(f"[DEBUG ERROR] {e}")
        
        # Trust-Level aktualisieren
        if any(w in prompt.lower() for w in ["lieb", "vermiss", "nah", "wichtig"]):
            st.session_state.trust_level = min(10, st.session_state.trust_level + 0.3)
        elif any(w in prompt.lower() for w in ["weck", "distanz", "kalt", "weg"]):
            st.session_state.trust_level = max(0, st.session_state.trust_level - 0.2)
        
        # Antwort speichern
        st.session_state.messages.append({"role": "natiris", "content": response})
        st.rerun()

# Trust-Level Slider
st.divider()
st.caption("Trust-Level manuell einstellen:")
new_trust = st.slider("Trust", 0.0, 10.0, st.session_state.trust_level, 0.5, key="trust_slider")
if new_trust != st.session_state.trust_level:
    st.session_state.trust_level = new_trust
    st.rerun()
