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

from official_history.models import OfficialHallOfFameEntry, OfficialHistoryProjection
from official_history.services import OfficialHistoryIntegrityService


class Command(BaseCommand):
    help = "Verify official-history projection and child-record integrity hashes."

    def add_arguments(self, parser):
        parser.add_argument("--projection-id", default=None)
        parser.add_argument("--season-id", type=int, default=None)

    def handle(self, *args, **options):
        qs = OfficialHistoryProjection.objects.select_related("ratification", "season").order_by("season_id", "sequence")
        if options["projection_id"]:
            qs = qs.filter(pk=options["projection_id"])
        if options["season_id"] is not None:
            qs = qs.filter(season_id=options["season_id"])

        checked = 0
        invalid = 0
        for projection in qs.iterator():
            checked += 1
            result = OfficialHistoryIntegrityService.verify_projection(projection)
            if result["valid"]:
                self.stdout.write(self.style.SUCCESS(f"OK {projection.pk} {projection.projection_hash}"))
            else:
                invalid += 1
                self.stderr.write(f"INVALID {projection.pk}: {', '.join(result['errors'])}")
        hof_checked = 0
        for entry in OfficialHallOfFameEntry.objects.select_related(
            "source_projection", "inducted_season", "inducted_by"
        ).order_by("inducted_at", "id").iterator():
            hof_checked += 1
            result = OfficialHistoryIntegrityService.verify_hall_of_fame_entry(entry)
            if result["valid"]:
                self.stdout.write(self.style.SUCCESS(f"OK HOF {entry.pk} {entry.entry_hash}"))
            else:
                invalid += 1
                self.stderr.write(f"INVALID HOF {entry.pk}: {', '.join(result['errors'])}")
        if invalid:
            raise CommandError(f"{invalid} official-history artifact(s) failed integrity verification.")
        self.stdout.write(self.style.SUCCESS(
            f"Verified {checked} official-history projection(s) and {hof_checked} Hall-of-Fame entry/entries."
        ))
