import streamlit as st
import pandas as pd
import openai

# Initialize OpenAI client
client = openai.OpenAI(api_key="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")

# Load Multiple Datasets
@st.cache_data
def load_data(file_paths):
    dataframes = {file_path: pd.read_csv(file_path, low_memory=False) for file_path in file_paths}
    combined_data = pd.concat(dataframes.values(), ignore_index=True)
    return combined_data, dataframes

# File paths for multiple datasets
file_paths = ["Ageing Survey 2023.csv", "Digital Bank.csv", "Digital Well-Being.csv", "Economic Sentiments Poll.csv", "IndSights Sustainability Efforts.csv", "News Consumption Study.csv", "Perception of Tourism in SG.csv", "Perceptions on Homelessness.csv", "Smart Nation.csv"]
data, individual_dataframes = load_data(file_paths)

# Streamlit App Interface
st.title("Rysense Data Interactive Q&A App")

# Display Dataset Preview
if st.checkbox("Show Combined Dataset Preview"):
    st.write(data.head())

# Option to View Individual Files
if st.checkbox("Show Individual Dataset Previews"):
    for file_name, df in individual_dataframes.items():
        st.write(f"### Preview of {file_name}")
        st.write(df.head())

# Generate a summary of the dataset for input tokens
input_tokens = f"""
Combined survey data includes {len(data)} rows and {len(data.columns)} columns.
Column names are: {', '.join(data.columns[:5])} (and more).
Example row: {data.iloc[0].to_dict()}
"""
#st.write(input_tokens)
# Initialize the conversation history and question cache in session state
if "message_history" not in st.session_state:
    st.session_state.message_history = [
        {"role": "system", "content": "You are a data analyst specializing in survey analysis."},
        {"role": "user", "content": input_tokens}
    ]

if "question_cache" not in st.session_state:
    st.session_state.question_cache = {}

# User Interaction
user_question = st.text_input("Your Question:", "")

if st.button("Submit Question"):
    if user_question.strip():
        # Check if the result is already in the cache
        if user_question in st.session_state.question_cache:
            st.subheader("Cached Response:")
            st.write(st.session_state.question_cache[user_question])
        else:
            # Add the user's question to the conversation history
            st.session_state.message_history.append({"role": "user", "content": user_question})

            # Call the GPT-4 API
            response = client.chat.completions.create(
                model="gpt-4o-mini",
                messages=st.session_state.message_history
            )

            # Extract GPT's reply
            gpt_reply = response.choices[0].message.content

            # Cache the result
            st.session_state.question_cache[user_question] = gpt_reply

            # Display GPT's reply
            st.subheader("Response:")
            st.write(gpt_reply)

            # Add GPT's reply to the conversation history
            st.session_state.message_history.append({"role": "assistant", "content": gpt_reply})
    else:
        st.warning("Please enter a question before submitting.")

# Option to Reset Context
if st.button("Reset Context"):
    st.session_state.message_history = [
        {"role": "system", "content": "You are a data analyst specializing in survey analysis."},
        {"role": "user", "content": input_tokens}
    ]
    st.session_state.question_cache = {}
    st.success("Context has been reset.")

# Display Cached Questions
if st.checkbox("Show Cached Questions"):
    if st.session_state.question_cache:
        st.write("### Cached Questions and Responses")
        for question, response in st.session_state.question_cache.items():
            st.write(f"**Question:** {question}")
            st.write(f"**Response:** {response}")
    else:
        st.info("No cached questions yet.")

# Summarize older messages to save tokens if history is too long
if len(st.session_state.message_history) > 10:
    summarized_history = " ".join([msg["content"] for msg in st.session_state.message_history[:-5]])
    st.session_state.message_history = [
        {"role": "system", "content": "You are a data analyst specializing in survey analysis."},
        {"role": "user", "content": f"Summary of previous conversation: {summarized_history}"}
    ] + st.session_state.message_history[-5:]

st.write("Type 'exit' in the console to terminate the backend session if running locally.")
