import streamlit as st
from openai import OpenAI
import json


# Set up the Streamlit app
st.title("BuffTeks Chatbot")
st.subheader("Chat with the [DeepSeek](https://www.deepseek.com/)-powered AI assistant!")
st.info("Feel free to chat with the chatbot! Just a heads up, you have 10 messages to use.")
with st.expander("See Source Code"):
            with open(__file__, "r") as f:
                st.code(f.read(), language="python")

# Load API credentials from config.json
with open('chatbot_config.json') as config_file:
    config = json.load(config_file)
    openai_api_base_url = config["api_url"]
    openai_api_key = config["api_key"]

client = OpenAI(api_key=openai_api_key, base_url=openai_api_base_url)

# Initialize session state to store chat history and message count
if "messages" not in st.session_state:
    st.session_state.messages = []
if "message_count" not in st.session_state:
    st.session_state.message_count = 0

# Set the maximum number of user messages
MAX_USER_MESSAGES =  10

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

# Chat input
if st.session_state.message_count < MAX_USER_MESSAGES:
    if prompt := st.chat_input("Type your message..."):
        # Add user message to chat history
        st.session_state.messages.append({"role": "user", "content": prompt})
        st.session_state.message_count += 1
        with st.chat_message("user"):
            st.markdown(prompt)

        # Call DeepSeek for a response
        with st.chat_message("assistant"):
            stream = client.chat.completions.create(
                model="deepseek-chat",
                messages=[
                    {"role": m["role"], "content": m["content"]}
                    for m in st.session_state.messages
                ],
                stream=True,
            )
            response = st.write_stream(stream)
        st.session_state.messages.append({"role": "assistant", "content": response})

else:
    st.warning("You have reached the maximum number of messages allowed.")
      
if st.button("Clear Chat"):
    st.session_state.messages = []