"""Certificate report charts for CxO dashboards.

Producer module — shipped in runbooks wheel.
Consumer: from runbooks.security.cert_report_charts import cert_expiry_distribution
"""

import pandas as pd

try:
    import plotly.express as px
    import plotly.graph_objects as go
except ImportError:
    px = None
    go = None


def cert_expiry_distribution(certs: list[dict]) -> "go.Figure":
    """Certificate expiry distribution bar chart."""
    if px is None:
        raise ImportError("plotly required: pip install 'runbooks[analytics]'")
    buckets = {"EXPIRED": 0, "< 7d": 0, "< 30d": 0, "< 90d": 0, "> 90d": 0}
    for c in certs:
        _raw = c.get("days_until_expiry")
        if _raw is None:
            _raw = c.get("days_to_expiry")
        days = _raw if _raw is not None else 999
        if days <= 0:
            buckets["EXPIRED"] += 1
        elif days <= 7:
            buckets["< 7d"] += 1
        elif days <= 30:
            buckets["< 30d"] += 1
        elif days <= 90:
            buckets["< 90d"] += 1
        else:
            buckets["> 90d"] += 1
    df = pd.DataFrame({"Bucket": list(buckets.keys()), "Count": list(buckets.values())})
    colors = ["#ef4444", "#f97316", "#f59e0b", "#3b82f6", "#22c55e"]
    fig = px.bar(
        df,
        x="Bucket",
        y="Count",
        color="Bucket",
        color_discrete_sequence=colors,
        title="Certificate Expiry Distribution (Live AWS)",
    )
    fig.update_layout(template="plotly_dark", showlegend=False)
    return fig


def cert_risk_by_account(certs: list[dict]) -> "go.Figure":
    """Risk heatmap: certs per account colored by urgency."""
    if px is None:
        raise ImportError("plotly required: pip install 'runbooks[analytics]'")
    rows = []
    for c in certs:
        _raw = c.get("days_until_expiry")
        if _raw is None:
            _raw = c.get("days_to_expiry")
        days = _raw if _raw is not None else 999
        risk = "critical" if days <= 7 else "warning" if days <= 30 else "attention" if days <= 90 else "valid"
        rows.append({"account": c.get("account_id", c.get("account_name", "unknown")), "risk": risk})
    df = pd.DataFrame(rows) if rows else pd.DataFrame({"account": [], "risk": [], "count": []})
    if len(df) > 0:
        df = df.groupby(["account", "risk"]).size().reset_index(name="count")
    fig = px.bar(
        df,
        x="account",
        y="count",
        color="risk",
        color_discrete_map={"critical": "#ef4444", "warning": "#f97316", "attention": "#3b82f6", "valid": "#22c55e"},
        title="Certificate Risk by Account",
    )
    fig.update_layout(template="plotly_dark", xaxis_tickangle=-45)
    return fig
