"""Dashboard summary and feed helpers for SwarmPay."""
from __future__ import annotations

from swarmpay.webhooks import WebhookDispatcher


def build_dashboard_summary(dispatcher: WebhookDispatcher) -> dict:
    """Aggregate top-level dashboard metrics from webhook/event state."""
    total_events = len(dispatcher.events)
    total_subscriptions = len(dispatcher.subscriptions)
    enabled_subscriptions = sum(1 for subscription in dispatcher.subscriptions if subscription.enabled)
    total_deliveries = len(dispatcher.deliveries)
    successful_deliveries = sum(1 for delivery in dispatcher.deliveries if delivery.success)
    failed_deliveries = total_deliveries - successful_deliveries
    pending_retries = sum(
        1
        for delivery in dispatcher.deliveries
        if not delivery.success and delivery.next_attempt_at > 0
    )
    escrow_funded_events = sum(
        1 for event in dispatcher.events if event.event_type == "escrow.funded"
    )

    return {
        "total_events": total_events,
        "total_subscriptions": total_subscriptions,
        "enabled_subscriptions": enabled_subscriptions,
        "total_deliveries": total_deliveries,
        "successful_deliveries": successful_deliveries,
        "failed_deliveries": failed_deliveries,
        "pending_retries": pending_retries,
        "escrow_funded_events": escrow_funded_events,
        "delivery_success_rate": (
            successful_deliveries / total_deliveries if total_deliveries else 0.0
        ),
    }


def build_dashboard_feed(dispatcher: WebhookDispatcher, limit: int = 20) -> list[dict]:
    """Create a reverse-chronological feed for dashboard activity."""
    items = []

    for event in dispatcher.events:
        items.append(
            {
                "kind": "event",
                "timestamp": event.created_at,
                "id": event.event_id,
                "title": event.event_type,
                "details": event.payload,
            }
        )

    for delivery in dispatcher.deliveries:
        items.append(
            {
                "kind": "delivery",
                "timestamp": delivery.delivered_at,
                "id": f"{delivery.event_id}:{delivery.subscription_id}:{delivery.attempt}",
                "title": "webhook.delivery.succeeded" if delivery.success else "webhook.delivery.failed",
                "details": {
                    "event_id": delivery.event_id,
                    "subscription_id": delivery.subscription_id,
                    "attempt": delivery.attempt,
                    "status_code": delivery.status_code,
                    "error": delivery.error,
                    "next_attempt_at": delivery.next_attempt_at,
                },
            }
        )

    items.sort(key=lambda item: item["timestamp"], reverse=True)
    return items[:max(limit, 0)]
