import streamlit as st
import os
from PIL import Image
import numpy as np
import pickle
from chatbot import Chatbot  # Assuming you have a chatbot module

# Function to save uploaded file
def save_uploaded_file(uploaded_file):
    try:
        if not os.path.exists('uploads'):
            os.makedirs('uploads')
        with open(os.path.join('uploads', uploaded_file.name), 'wb') as f:
            f.write(uploaded_file.getbuffer())
        return True
    except Exception as e:
        st.error(f"Error: {e}")
        return False

# Function to show dashboard content
def show_dashboard():
    st.header("Fashion Recommender System")
    chatbot = Chatbot()
    chatbot.load_data()

    # File upload section
    uploaded_file = st.file_uploader("Choose an image")
    if uploaded_file is not None:
        if save_uploaded_file(uploaded_file):
            # Display the uploaded image
            display_image = Image.open(uploaded_file)
            st.image(display_image)

            # Generate image caption
            image_path = os.path.join("uploads", uploaded_file.name)
            caption = chatbot.generate_image_caption(image_path)
            st.write("Generated Caption:", caption)

            # Use caption to get product recommendations
            _, recommended_products = chatbot.generate_response(caption)

            # Display recommended products
            col1, col2, col3, col4, col5 = st.columns(5)
            with col1:
                st.image(chatbot.images[recommended_products[0]['corpus_id']])
            with col2:
                st.image(chatbot.images[recommended_products[1]['corpus_id']])
            with col3:
                st.image(chatbot.images[recommended_products[2]['corpus_id']])
            with col4:
                st.image(chatbot.images[recommended_products[3]['corpus_id']])
            with col5:
                st.image(chatbot.images[recommended_products[4]['corpus_id']])

        else:
            st.header("Some error occurred in file upload")

    # Chatbot section
    user_question = st.text_input("Ask a question:")
    if user_question:
        bot_response, recommended_products = chatbot.generate_response(user_question)
        st.write("Chatbot:", bot_response)

        # Display recommended products
        for result in recommended_products:
            pid = result['corpus_id']
            product_info = chatbot.product_data[pid]
            st.write("Product Name:", product_info['productDisplayName'])
            st.write("Category:", product_info['masterCategory'])
            st.write("Article Type:", product_info['articleType'])
            st.write("Usage:", product_info['usage'])
            st.write("Season:", product_info['season'])
            st.write("Gender:", product_info['gender'])
            st.image(chatbot.images[pid])

# Main Streamlit app
def main():
    # Give title to the app
    st.title("Fashion Recommender System")

    # Show dashboard content directly
    show_dashboard()

# Run the main app
if __name__ == "__main__":
    main()