from django.core.management.base import BaseCommand, CommandError

from monitoring.models import WebsiteMonitor
from monitoring.services import run_due_monitors, run_monitor_check


class Command(BaseCommand):
    help = "Executa monitores de websites manualmente."

    def add_arguments(self, parser):
        parser.add_argument("--id", type=int, help="Executa apenas o monitor indicado.")
        parser.add_argument("--all", action="store_true", help="Executa todos os monitores ativos, mesmo que ainda não estejam vencidos.")
        parser.add_argument("--limit", type=int, default=None, help="Limita o número de monitores vencidos.")

    def handle(self, *args, **options):
        monitor_id = options.get("id")
        if monitor_id:
            try:
                check = run_monitor_check(monitor_id)
            except WebsiteMonitor.DoesNotExist as exc:
                raise CommandError("Monitor não encontrado.") from exc
            self.stdout.write(self.style.SUCCESS(
                f"{check.monitor}: {check.get_result_display()} · HTTP {check.http_status or '-'} · {check.response_time_ms or '-'} ms"
            ))
            return
        if options.get("all"):
            result = {"processed": 0, "up": 0, "degraded": 0, "down": 0, "errors": []}
            for monitor in WebsiteMonitor.objects.filter(is_active=True).order_by("pk"):
                try:
                    check = run_monitor_check(monitor)
                    result["processed"] += 1
                    result[check.result if check.result in {"up", "degraded", "down"} else "degraded"] += 1
                except Exception as exc:
                    result["errors"].append(str(exc))
        else:
            result = run_due_monitors(limit=options.get("limit"))
        self.stdout.write(self.style.SUCCESS(
            f"Processados: {result['processed']} · Operacionais: {result['up']} · Degradados: {result['degraded']} · Falhas: {result['down']}"
        ))
        for error in result["errors"]:
            self.stderr.write(str(error))
