import streamlit as st
import pandas as pd
from utils import (
    validate_csv, analyze_data, get_numeric_columns,
    get_categorical_columns, calculate_basic_stats
)
from dotenv import load_dotenv
import os
from pathlib import Path
import plotly.express as px
import plotly.graph_objects as go
import base64

def load_image_as_base64(image_path):
    with open(image_path, "rb") as img_file:
        return base64.b64encode(img_file.read()).decode()
    
st.set_page_config(
    page_title="Spiderx Rysense Data Analyzer",
    page_icon="assets/images/small-icon-black.png",
    layout="wide"
)

#st.write(logo_path)
st.sidebar.image("assets/images/logo.png", width=300)


# Create data directory if it doesn't exist
data_dir = Path("data")
data_dir.mkdir(exist_ok=True)

# Initialize session state
if 'selected_files' not in st.session_state:
    st.session_state.selected_files = {}

def plot_histogram(df, column):
    """Create a histogram for numeric data from files"""
    fig = px.histogram(df, x=column, title=f'Distribution of {column}')
    return fig

def plot_box(df, column):
    """Create a box plot for numeric data"""
    fig = px.box(df, y=column, title=f'Box Plot of {column}')
    return fig

def plot_scatter(df, x_col, y_col):
    """Create a scatter plot for two numeric columns"""
    fig = px.scatter(df, x=x_col, y=y_col, title=f'{x_col} vs {y_col}')
    return fig

def main():
    st.title("Spiderx AI Survey Analysis")
    
    # Check for API key
    load_dotenv()  # Load environment variables from .env

    api_key = os.getenv("OPENAI_API_KEY")

    if not api_key:
        st.error("⚠️ OpenAI API key not found. Please set the OPENAI_API_KEY environment variable.")
        return

    # File selection section
    st.header("1. Available CSV Files")

    # Get list of CSV files in data directory
    csv_files = list(data_dir.glob("*.csv"))
    if not csv_files:
        st.warning("No CSV files found in the 'data' directory. Please add CSV files to the 'data' folder.")
        st.markdown("""
        ### How to add files:
        1. Create a folder named 'data' in the project root (if not exists)
        2. Place your CSV files in the 'data' folder
        3. The files will appear here automatically
        """)
        return

    # File selection
    selected_file_paths = st.multiselect(
        "Select CSV files to analyze",
        options=csv_files,
        format_func=lambda x: x.name,
        help="Choose one or more CSV files from the data directory"
    )

    # Process selected files
    for file_path in selected_file_paths:
        if file_path.name not in st.session_state.selected_files:
            with file_path.open('rb') as f:
                is_valid, result = validate_csv(f)
                if is_valid:
                    st.session_state.selected_files[file_path.name] = result
                else:
                    st.error(f"Error in {file_path.name}: {result}")

    # Display data preview and visualizations
    if st.session_state.selected_files:
        # Create tabs for different sections
        tab1,  tab2 = st.tabs(["AI Analysis","Data Preview"])

        with tab2:
            st.header("Data Preview")
            # Show analysis information
            total_files = len(st.session_state.selected_files)
            st.info(f"""
            🔍 Analysis Details:
            - Total files selected: {total_files}
            - All files will be included in the analysis
            """)

            for filename, df in st.session_state.selected_files.items():
                with st.expander(f"Preview: {filename}"):
                    st.dataframe(
                        df.head(5),
                        use_container_width=True
                    )
                    st.text(f"Shape: {df.shape[0]} rows × {df.shape[1]} columns")


        with tab1:
            st.header("1. Ask Questions About Your Data")

            # Add checkbox for showing prompt
            #show_prompt = st.checkbox("Show API Prompt", help="Display the prompt being sent to OpenAI")

            question = st.text_area(
                "Enter your question",
                placeholder="Example: What is the average value in column X? Compare data across all files.",
                help="Ask any question about your data - the AI will analyze all selected files"
            )

            if st.button("Analyze", type="primary"):
                if question:
                    with st.spinner("Analyzing your data..."):
                        success, response, prompt = analyze_data(question, st.session_state.selected_files)

                        if success:
                            # if show_prompt:
                             #   with st.expander("📝 API Prompt", expanded=True):
                              #      st.text_area("Complete prompt sent to OpenAI:", prompt, height=300) """

                            st.header("Analysis Results")
                            st.write(response)
                        else:
                            st.error(response)
                else:
                    st.warning("Please enter a question to analyze.")

        # Clear data button
        if st.button("Clear Selected Files"):
            st.session_state.selected_files = {}
            st.rerun()
    else:
        st.info("👆 Start by selecting CSV files from the data directory")

    # Footer
    st.markdown("---")
    st.markdown("""
        <div style='text-align: center'>
            <p>Built with SpiderX AI</p>
        </div>
        """, unsafe_allow_html=True)

if __name__ == "__main__":
    main()