"""Model comparison section for experiment analysis."""

import pandas as pd
import streamlit as st

from entropice.dashboard.plots.experiment_comparison import create_top_models_bar_chart
from entropice.dashboard.utils.formatters import format_metric_name


@st.fragment
def render_model_comparison(summary_df: pd.DataFrame, available_metrics: list[str]):
    """Render model comparison section.

    Args:
        summary_df: Summary DataFrame with all results
        available_metrics: List of available metrics

    """
    st.header("🏆 Model Performance Comparison")

    st.markdown(
        """
        This section shows the best performing models for each task.
        """
    )

    # Determine metrics to use per task
    task_metric_map = {
        "binary": "f1",
        "count_regimes": "f1_weighted",
        "density_regimes": "f1_weighted",
        "count": "r2",
        "density": "r2",
    }

    # Split selection
    split = st.selectbox("Data Split", options=["test", "train", "complete"], index=0, key="model_split")

    # Get unique tasks
    unique_tasks = summary_df["task"].unique()

    # For each task, show the best models
    for task in sorted(unique_tasks):
        # Determine the metric for this task
        metric = task_metric_map.get(task, available_metrics[0])
        metric_col = f"{split}_{metric}"

        if metric_col not in summary_df.columns:
            # Fall back to first available metric
            metric = available_metrics[0]
            metric_col = f"{split}_{metric}"

        st.subheader(f"{task.replace('_', ' ').title()}")

        # Filter data for this task
        task_df = summary_df[summary_df["task"] == task].copy()

        # Create visualization
        try:
            fig = create_top_models_bar_chart(task_df, metric, task, split, top_n=10)
            st.plotly_chart(fig, width="stretch")
        except Exception as e:
            st.error(f"Could not create model comparison chart for {task}: {e}")

        # Show table in expander
        with st.expander("Show Top 10 Models Table", expanded=False):
            top_models = task_df.nlargest(10, metric_col)[
                ["model", "grid", "level", "target", metric_col, "method"]
            ].copy()
            top_models.columns = ["Model", "Grid", "Level", "Target", format_metric_name(metric), "Method"]
            st.dataframe(
                top_models.reset_index(drop=True),
                width="stretch",
                hide_index=True,
            )

        st.divider()
