import streamlit as st
import google.generativeai as genai
from dotenv import load_dotenv
import os
from router import agent_router  

# Load API key
load_dotenv()
genai.configure(api_key=os.getenv("gemini_api_key"))

# Streamlit UI setup
st.set_page_config(page_title="Stock Market Consultant 💹", layout="wide")
st.title("💬 Stock Market Consultant")

# Initialize chat history
if "messages" not in st.session_state:
    st.session_state.messages = []

# --- Chat container: show messages ABOVE the input ---
chat_container = st.container()

# Display previous chat messages (top to bottom)
with chat_container:
    for msg in st.session_state.messages:
        with st.chat_message(msg["role"]):
            st.markdown(msg["content"])

# --- Input area stays at the BOTTOM ---
st.markdown("---")  # separator line for clarity

with st.container():
    with st.form(key="chat_form", clear_on_submit=True):
        user_input = st.text_input(
            "💬 Type your question about stocks or crypto:",
            placeholder="e.g., search for analysing,risk factors and comparing of stocks",
            label_visibility="collapsed"
        )
        submitted = st.form_submit_button("Send")

    if submitted and user_input:
        # Display user message
        with st.chat_message("user"):
            st.markdown(user_input)
        st.session_state.messages.append({"role": "user", "content": user_input})

        # Get AI/agent response
        with st.chat_message("assistant"):
            with st.spinner("Analyzing market data..."):
                response_text = agent_router(user_input)
                st.markdown(response_text)

        # Save assistant message
        st.session_state.messages.append({"role": "assistant", "content": response_text})
