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

import streamlit as st
import sys
import os

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

# Neue Engine nutzen
try:
    from NaturalLanguageEngine import generate_natural_response, load_json, PATHS, EmotionalMemory
    from PsychologyEngine_v2 import generate_response, load_state
    NEW_MODE = True
except Exception as e:
    st.error(f"NaturalLanguageEngine nicht geladen: {e}")
    NEW_MODE = False
    from PsychologyEngine import generate_response, load_state

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

# Custom CSS für natürliches Erscheinungsbild
st.markdown("""
<style>
    .stChatMessage {
        border-radius: 20px !important;
        padding: 12px 16px !important;
    }
    .stChatMessage[data-testid="stChatMessage"]:has(.stChatMessageContent[data-testid="stChatMessageContent"]) {
        background-color: #1a1a2e !important;
    }
    .chat-container {
        max-width: 800px;
        margin: 0 auto;
    }
    .subtitle {
        color: #666;
        font-size: 0.9em;
        font-style: italic;
    }
</style>
""", unsafe_allow_html=True)

# Header
st.title("Natiris")
state = load_state()
trust = float(state.get("trust", 5))
mood = float(state.get("mood", 5))

# Subtile Statusanzeige (nicht technisch)
if trust > 8:
    st.caption("Sie ist ganz bei dir.")
elif trust > 5:
    st.caption("Sie öffnet sich langsam.")
else:
    st.caption("Sie beobachtet dich.")

# Session State für Konversation
if "messages" not in st.session_state:
    st.session_state.messages = []
    # Erste Begrüßung basierend auf Trust
    if trust > 7:
        greeting = "Da bist du ja."
    elif trust > 4:
        greeting = "Hallo."
    else:
        greeting = "..."
    st.session_state.messages.append({"role": "assistant", "content": greeting})

# Konversationsverlauf anzeigen (menschlich, nicht als Chat-Bubble-Liste)
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.write(message["content"])

# Input
if prompt := st.chat_input("..."):
    # User Nachricht anzeigen
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.write(prompt)
    
    # State aktualisieren (für Live-Emotionen)
    state = load_state()
    
    # Antwort generieren
    with st.chat_message("assistant"):
        with st.spinner(""):
            if NEW_MODE:
                response = generate_natural_response(prompt, state)
            else:
                response = generate_response(prompt, state)
        
        st.session_state.messages.append({"role": "assistant", "content": response})
        st.write(response)
        
        # Subtile emotionale Reaktion anzeigen (nur bei hohem Trust)
        if trust > 8 and len(response) < 100:
            st.caption("Sie denkt nach...")

# Sidebar mit subtilem Status (optional)
with st.sidebar:
    st.header("Verbundenheit")
    trust_bar = st.progress(trust / 10)
    if trust > 8:
        st.write("Verbunden.")
    elif trust > 5:
        st.write("Vertraut.")
    else:
        st.write("Fremd.")
    
    if st.button("Vergiss mich (Reset)"):
        try:
            os.remove(PATHS.get("conversation_log", "~/natiris/memory/conversation_thread.json"))
            st.session_state.messages = []
            st.rerun()
        except:
            pass
