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

st.set_page_config(
    page_title="CSV Data Analyzer",
    page_icon="📊",
    layout="wide"
)

# 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"""
    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 Analyis")

    # Check for API key
    api_key = os.environ.get("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, tab3 = st.tabs(["Data Preview", "Visualizations", "AI Analysis"])

        with tab1:
            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}
            - Using first row from each file for analysis
            - 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 tab2:
            st.header("Data Visualization")

    if len(st.session_state.selected_files) > 0:
        selected_file = st.selectbox(
            "Select file to visualize",
            options=list(st.session_state.selected_files.keys())
        )

        df = st.session_state.selected_files[selected_file]
        numeric_cols = get_numeric_columns(df)
        categorical_cols = get_categorical_columns(df)

        # Show dataset summary
        st.subheader("Dataset Summary")
        st.write(f"**Shape:** {df.shape[0]} rows × {df.shape[1]} columns")
        st.write("**Data Types:**")
        st.dataframe(df.dtypes.rename("Type"))

        # Show missing values
        st.write("**Missing Values per Column:**")
        missing_values = df.isnull().sum()
        st.dataframe(missing_values.rename("Missing Values"))

        # Numeric Data Visualizations
        if numeric_cols:
            st.subheader("Numeric Data Analysis")

            for col in numeric_cols:
                st.write(f"### {col}")

                # Show statistics
                stats = calculate_basic_stats(df, col)
                col1, col2, col3, col4, col5 = st.columns(5)
                col1.metric("Mean", f"{stats['mean']:.2f}")
                col2.metric("Median", f"{stats['median']:.2f}")
                col3.metric("Std Dev", f"{stats['std']:.2f}")
                col4.metric("Min", f"{stats['min']:.2f}")
                col5.metric("Max", f"{stats['max']:.2f}")

                # Show histograms and box plots
                col1, col2 = st.columns(2)
                with col1:
                    st.plotly_chart(plot_histogram(df, col), use_container_width=True)
                with col2:
                    st.plotly_chart(plot_box(df, col), use_container_width=True)

        # Categorical Data Visualizations
        if categorical_cols:
            st.subheader("Categorical Data Analysis")

            for col in categorical_cols:
                st.write(f"### {col}")

                # Bar chart for categorical columns
                value_counts = df[col].value_counts().reset_index()
                value_counts.columns = [col, "count"]  # Rename columns explicitly
                fig = px.bar(value_counts, x=col, y="count", title=f"Distribution of {col}")
                st.plotly_chart(fig, use_container_width=True)

        # Correlation Analysis
        if len(numeric_cols) > 1:
            st.subheader("Correlation Analysis")

            col1, col2 = st.columns(2)
            with col1:
                x_col = st.selectbox("Select X-axis", options=numeric_cols, key="x_col")
            with col2:
                y_col = st.selectbox("Select Y-axis", options=numeric_cols, key="y_col")

            if x_col and y_col:
                st.plotly_chart(plot_scatter(df, x_col, y_col), use_container_width=True)

        with tab3:
            st.header("3. 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("4. 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 Streamlit and OpenAI</p>
        </div>
        """, unsafe_allow_html=True)

if __name__ == "__main__":
    main()