from django.core.management.base import BaseCommand, CommandError
from club_finance.models import AccountingPeriod
from club_finance.regulatory import RegulatoryCalculationService


class Command(BaseCommand):
    help = "Run accrual-based rolling regulatory FFP assessment for an accounting period"

    def add_arguments(self, parser):
        parser.add_argument("period_id")

    def handle(self, *args, **options):
        try:
            period = AccountingPeriod.objects.select_related("club", "season").get(pk=options["period_id"])
            assessment = RegulatoryCalculationService.assess(club=period.club, target_period=period)
        except AccountingPeriod.DoesNotExist as exc:
            raise CommandError("Accounting period not found") from exc
        except Exception as exc:
            raise CommandError(str(exc)) from exc
        self.stdout.write(self.style.SUCCESS(
            f"assessment={assessment.pk} status={assessment.status} rolling_result={assessment.rolling_result}"
        ))
