"""Experiment Analysis page: Compare multiple training runs within an experiment."""

import streamlit as st

from entropice.dashboard.sections.experiment_feature_importance import render_feature_importance_analysis
from entropice.dashboard.sections.experiment_grid_analysis import render_grid_level_analysis
from entropice.dashboard.sections.experiment_inference_maps import render_inference_maps_section
from entropice.dashboard.sections.experiment_model_comparison import render_model_comparison
from entropice.dashboard.sections.experiment_overview import (
    render_experiment_overview,
    render_experiment_sidebar,
)
from entropice.dashboard.utils.loaders import (
    create_experiment_summary_df,
    load_experiment_training_results,
)


def render_experiment_analysis_page():
    """Render the Experiment Analysis page of the dashboard."""
    st.title("🔬 Experiment Analysis")

    st.markdown(
        """
        Analyze and compare multiple training runs within an experiment.
        Select an experiment from the sidebar to explore:
        - How grid levels affect performance
        - Best models across different tasks and targets
        - Feature importance patterns
        """
    )

    # Experiment selection
    selected_experiment = render_experiment_sidebar()

    if selected_experiment is None:
        st.info("👈 Select an experiment from the sidebar to begin analysis.")
        st.stop()

    assert selected_experiment is not None, "Experiment must be selected"

    # Load experiment results
    with st.spinner(f"Loading results for experiment: {selected_experiment}..."):
        training_results = load_experiment_training_results(selected_experiment)

    if not training_results:
        st.warning(f"No training results found in experiment: {selected_experiment}")
        st.stop()

    # Create summary DataFrame
    summary_df = create_experiment_summary_df(training_results)

    # Get available metrics
    metric_columns = [col for col in summary_df.columns if col.startswith("test_")]
    available_metrics = [col.replace("test_", "") for col in metric_columns]

    if not available_metrics:
        st.error("No metrics found in the experiment results.")
        st.stop()

    # Render analysis sections
    render_experiment_overview(selected_experiment, training_results, summary_df)

    st.divider()

    render_grid_level_analysis(summary_df, available_metrics)

    st.divider()

    render_model_comparison(summary_df, available_metrics)

    st.divider()

    render_feature_importance_analysis(training_results)

    st.divider()

    render_inference_maps_section(selected_experiment, training_results)

    st.divider()

    # Raw data section
    st.header("📄 Raw Experiment Data")
    with st.expander("View Complete Summary DataFrame"):
        st.dataframe(summary_df, width="stretch")
