"""
Streamlit page for the Warehouse AI Chatbot
Save as: app/pages/4_💬_Chatbot.py
"""
import streamlit as st
import sys
from pathlib import Path
from dotenv import load_dotenv
import os

# Load environment variables from .env file
load_dotenv()
GROQ_API_KEY = os.getenv("GROQ_API_KEY")


# Add project root to path
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

from utils.warehouse_chatbot import WarehouseChatbot

st.set_page_config(page_title="Warehouse AI Assistant", page_icon="💬", layout="wide")

st.title("💬 Warehouse AI Assistant")
st.caption("Powered by LangChain & Groq (FREE) - Ask me anything about your inventory!")

# Initialize chatbot in session state
if 'chatbot' not in st.session_state:
    # Check for API key
    # api_key = st.secrets.get("GROQ_API_KEY", None) if hasattr(st, 'secrets') else None
    api_key = os.getenv("GROQ_API_KEY", None)
    
    if not api_key:
        st.error("⚠️ Groq API key not found!")
        st.info("""
        Please set your GROQ_API_KEY (FREE tier available!):
        
        **Step 1:** Get free API key at https://console.groq.com
        
        **Step 2:** Create `.streamlit/secrets.toml` with:
        ```toml
        GROQ_API_KEY = "your-api-key-here"
        ```
        
        **Or set environment variable:**
        ```bash
        export GROQ_API_KEY='your-api-key-here'
        ```
        """)
        st.stop()
    
    try:
        st.session_state.chatbot = WarehouseChatbot(api_key=api_key)
        st.success("✅ Chatbot initialized successfully!")
    except Exception as e:
        st.error(f"Error initializing chatbot: {e}")
        st.stop()

if 'messages' not in st.session_state:
    st.session_state.messages = [
        {
            "role": "assistant",
            "content": "👋 Hi! I'm your AI warehouse assistant. I can help you with:\n\n"
                      "• Order statistics and trends\n"
                      "• Inventory levels and SKU information\n"
                      "• Product performance analysis\n"
                      "• Forecasting insights\n\n"
                      "What would you like to know?"
        }
    ]

# Sidebar with example queries
with st.sidebar:
    st.markdown("### 💡 Example Questions")
    
    example_queries = [
        "How many total orders do we have?",
        "What are our top 5 best-selling SKUs?",
        "Show me recent order trends",
        "Which SKUs should I restock?",
        "Tell me about SKU-9304489678738",
        "What's our total inventory value?"
    ]
    
    st.markdown("Try asking:")
    for query in example_queries:
        if st.button(query, key=f"example_{query}", width='stretch'):
            st.session_state.user_input = query
    
    st.divider()
    
    if st.button("🗑️ Clear Conversation", width='stretch'):
        st.session_state.messages = [st.session_state.messages[0]]
        st.session_state.chatbot.clear_history()
        st.rerun()

# Display chat messages
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

# Chat input
if prompt := st.chat_input("Ask me anything about your warehouse..."):
    # Add user message to chat
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)
    
    # Get bot response
    with st.chat_message("assistant"):
        with st.spinner("Thinking..."):
            try:
                response = st.session_state.chatbot.chat(prompt)
                st.markdown(response)
                st.session_state.messages.append({"role": "assistant", "content": response})
            except Exception as e:
                error_msg = f"Sorry, I encountered an error: {str(e)}"
                st.error(error_msg)
                st.session_state.messages.append({"role": "assistant", "content": error_msg})

# Handle example query clicks
if 'user_input' in st.session_state:
    prompt = st.session_state.user_input
    del st.session_state.user_input
    
    st.session_state.messages.append({"role": "user", "content": prompt})
    
    try:
        response = st.session_state.chatbot.chat(prompt)
        st.session_state.messages.append({"role": "assistant", "content": response})
    except Exception as e:
        error_msg = f"Sorry, I encountered an error: {str(e)}"
        st.session_state.messages.append({"role": "assistant", "content": error_msg})
    
    st.rerun()