# stacksage/ai/summarizer.py
from typing import Any, Dict, List


def summarize_analysis(analysis: Dict[str, Any]) -> Dict[str, Any]:
    """
    Input: full analysis object
    Output: concise executive summary + top savings drivers
    """
    findings: List[Dict[str, Any]] = analysis.get("findings", [])
    total_savings = float(analysis.get("estimated_monthly_savings", 0) or 0)
    total_cost = float(analysis.get("estimated_monthly_cost", 0) or 0)
    # Top savings drivers
    sorted_findings = sorted(
        findings,
        key=lambda f: float(f.get("estimated_monthly_savings_usd", 0) or 0),
        reverse=True,
    )
    top = sorted_findings[:5]
    drivers = [
        {
            "type": f.get("type"),
            "id": f.get("id"),
            "region": f.get("region"),
            "savings": float(f.get("estimated_monthly_savings_usd", 0) or 0),
            "recommended_action": f.get("recommended_action") or f.get("action"),
        }
        for f in top
    ]
    summary_text = (
        (
            f"Potential monthly savings: ${total_savings:.2f}. "
            f"Current cost (flagged resources): ${total_cost:.2f}. "
            f"Primary drivers: "
            + ", ".join(
                [f"{d['type']}({d['id']}): ${d['savings']:.2f}" for d in drivers]
            )
        )
        if drivers
        else (
            f"Potential monthly savings: ${total_savings:.2f}. "
            f"Current cost (flagged resources): ${total_cost:.2f}. "
            "No high-impact drivers identified."
        )
    )
    return {
        "text": summary_text,
        "top_drivers": drivers,
    }
