from django.core.management.base import BaseCommand
from django.db.models import Count, Max, Min
from django.utils import timezone

from api.models import EngineResponseQuarantine, IntegrationOutbox, PostCommitDelivery


class Command(BaseCommand):
    help = "Report Resource Booking integration outbox state, lag, attempts, and recent errors."

    def add_arguments(self, parser):
        parser.add_argument("--errors", type=int, default=10)

    def handle(self, *args, **options):
        now = timezone.now()
        summary = IntegrationOutbox.objects.values("status").annotate(
            member_count=Count("id"),
            transaction_count=Count("transport_sequence", distinct=True),
            oldest=Min("created_at"),
            maximum_sequence=Max("transport_sequence"),
        ).order_by("status")
        for row in summary:
            age = (now - row["oldest"]).total_seconds() if row["oldest"] else 0
            self.stdout.write(
                f"{row['status']}: transactions={row['transaction_count']} "
                f"members={row['member_count']} max_source_sequence={row['maximum_sequence'] or 0} "
                f"oldest_age_seconds={age:.3f}"
            )
        errors = IntegrationOutbox.objects.exclude(last_error__isnull=True).order_by("-created_at")[
            : options["errors"]
        ]
        for event in errors:
            self.stdout.write(
                f"event_id={event.event_id} change_set_id={event.change_set_id} "
                f"source_sequence={event.transport_sequence} state={event.status} attempts={event.attempts} "
                f"correlation_id={event.correlation_id or '-'} error={event.last_error}"
            )
        delivery_summary = PostCommitDelivery.objects.values("status").annotate(count=Count("id")).order_by("status")
        for row in delivery_summary:
            self.stdout.write(f"post_commit_delivery.{row['status']}: count={row['count']}")
        quarantine_summary = (
            EngineResponseQuarantine.objects.values("reason")
            .annotate(count=Count("id"))
            .order_by("reason")
        )
        for row in quarantine_summary:
            self.stdout.write(f"engine_quarantine.{row['reason']}: count={row['count']}")
