from __future__ import annotations
from dataclasses import dataclass
from typing import List, Dict, Any
from datetime import timedelta

from ..process_mining.mining import VariantResult


@dataclass
class Insight:
    title: str
    summary: str
    data: Dict[str, Any]


def render_insights_text(insights: List[Insight]) -> str:
    lines = []
    for i, ins in enumerate(insights, 1):
        lines.append(f"{i}. {ins.title}\n   {ins.summary}")
    return "\n".join(lines)


def build_procurement_insights(
    top_variants: List[VariantResult],
    slow_cases: List[tuple[str, timedelta]],
    esg_flags: List[tuple[str, float]],
) -> List[Insight]:
    insights: List[Insight] = []

    if top_variants:
        insights.append(
            Insight(
                title="Top process variants (P2P execution paths)",
                summary="Common P2P paths were detected; standardize the top variant and reduce rework in uncommon paths.",
                data={"variants": [{"path": v.variant, "count": v.count} for v in top_variants]},
            )
        )

    if slow_cases:
        insights.append(
            Insight(
                title="Bottlenecks detected (slowest cases)",
                summary="These cases show the longest lead times; investigate approval delays, invoice exceptions, or GR waits.",
                data={"slow_cases": [{"case_id": c, "lead_time_hours": lt.total_seconds() / 3600.0} for c, lt in slow_cases]},
            )
        )

    if esg_flags:
        insights.append(
            Insight(
                title="ESG risk flags",
                summary="Some suppliers show lower ESG scores; consider corrective actions or diversified sourcing.",
                data={"esg_flags": [{"supplier_id": s, "score": sc} for s, sc in esg_flags]},
            )
        )

    return insights

