"""Grid-level analysis section for experiment comparison."""

import pandas as pd
import streamlit as st

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


@st.fragment
def render_grid_level_analysis(summary_df: pd.DataFrame, available_metrics: list[str]):
    """Render grid-level analysis section.

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

    """
    st.header("📐 Grid Level Analysis")

    st.markdown(
        """
        This section analyzes how different grid levels affect model performance.
        Compare performance across grid types (hex vs healpix) and resolution levels.
        Metrics are automatically selected based on the task type.
        """
    )

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

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

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

    # Create plots for each task
    for task in sorted(unique_tasks):
        # Determine the metric for this task
        metric = task_metric_map.get(task, available_metrics[0])

        # Check if metric is available
        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()} - {format_metric_name(metric)}")

        # Filter data for this task
        task_df = summary_df[summary_df["task"] == task]

        # Create grid-level comparison plot
        try:
            fig = create_grid_level_comparison_plot(task_df, metric, split)
            st.plotly_chart(fig, width="stretch")
        except Exception as e:
            st.error(f"Could not create grid-level comparison plot for {task}: {e}")

        # Show statistics by grid level for this task
        if metric_col in task_df.columns:
            stats = (
                task_df.groupby(["grid", "level"])[metric_col].agg(["mean", "std", "min", "max", "count"]).reset_index()
            )
            stats.columns = ["Grid", "Level", "Mean", "Std Dev", "Min", "Max", "Count"]
            with st.expander(f"Show {format_metric_name(metric)} Statistics by Grid Level", expanded=False):
                st.dataframe(stats.sort_values("Mean", ascending=False), width="stretch", hide_index=True)
