from datetime import date, timedelta

from django.core.management.base import BaseCommand
from django.db import transaction

from epdb.models import JobLog


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            "--cleanup",
            type=int,
            default=None,
            help="Remove all logs older than this number of days. Default is None, which does not remove any logs.",
        )

    @transaction.atomic
    def handle(self, *args, **options):
        if options["cleanup"] is not None:
            cleanup_dt = date.today() - timedelta(days=options["cleanup"])
            print(JobLog.objects.filter(created__lt=cleanup_dt).delete())

        logs = JobLog.objects.filter(status="INITIAL")
        print(f"Found {logs.count()} logs to update")
        updated = 0
        for log in logs:
            res = log.check_for_update()
            if res:
                updated += 1

        print(f"Updated {updated} logs")

        from django.db.models import Count

        qs = JobLog.objects.values("status").annotate(total=Count("status"))
        for r in qs:
            print(r["status"], r["total"])
