import logging
import pandas as pd
from typing import Dict

logger = logging.getLogger(__name__)


def calculate_summary_metrics(
    cell_summary: pd.DataFrame, agent_outcomes: pd.DataFrame
) -> Dict:
    logger.info("Calculating summary metrics...")
    initial_eat_rate = cell_summary["initial_eat_rate"].mean()
    total_eat_rate = cell_summary["total_eat_rate"].mean()
    winners_rate = cell_summary["winners_rate"].mean()
    median_tte = cell_summary["median_tte"].mean()
    rmst = cell_summary["rmst"].mean()
    total_winners = cell_summary["winners_count"].sum()
    data_quality_rate = cell_summary["data_quality_rate"].mean()
    invalid_rate = cell_summary["invalid_rate"].mean()
    valid_agent_trajectories = float(agent_outcomes["is_valid_outcome"].sum())
    invalid_agent_trajectories = float(agent_outcomes["is_invalid_outcome"].sum())
    metrics = {
        "overall_results": {
            "initial_eat_rate": initial_eat_rate,
            "total_eat_rate": total_eat_rate,
            "winners_rate": winners_rate,
            "median_tte": f"{median_tte:.1f} steps",
            "rmst": f"{rmst:.2f}",
            "total_winners": f"{total_winners:.0f}",
        },
        "data_quality": {
            "data_quality_rate": f"{data_quality_rate:.1%}",
            "invalid_outcome_rate": f"{invalid_rate:.1%}",
            "valid_agent_trajectories": f"{valid_agent_trajectories:.0f}",
            "invalid_agent_trajectories": f"{invalid_agent_trajectories:.0f}",
        },
    }
    logger.info("✓ Calculated summary metrics")
    return metrics
