from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import timedelta


class Command(BaseCommand):
    help = 'Penalizes students who abandoned flows for more than 24 hours.'

    def add_arguments(self, parser):
        parser.add_argument(
            '--hours', type=int, default=24,
            help='Number of hours after which a flow is considered abandoned (default: 24)'
        )
        parser.add_argument(
            '--dry-run', action='store_true',
            help='Show what would be penalized without actually penalizing'
        )

    def handle(self, *args, **options):
        from exams.models_flow import FlowRun
        from exams.services.points_ledger import penalize

        hours = options['hours']
        dry_run = options['dry_run']
        cutoff = timezone.now() - timedelta(hours=hours)

        abandoned_qs = FlowRun.objects.filter(
            status='ACTIVE',
            started_at__lt=cutoff,
            student__isnull=False,
        )

        total = abandoned_qs.count()
        self.stdout.write(f'Found {total} abandoned flows (active > {hours}h).')

        if dry_run:
            for run in abandoned_qs:
                self.stdout.write(f'  [DRY RUN] Would penalize {run.student.code} for flow "{run.flow.title}" (started {run.started_at})')
            self.stdout.write(self.style.WARNING('Dry run complete. No changes made.'))
            return

        count = 0
        for run in abandoned_qs:
            try:
                penalize(
                    run.student, 20,
                    f"Abandoned flow: {run.flow.title}",
                    code="FLOW_ABANDON",
                    evidence={'flow_run_id': run.pk, 'started_at': str(run.started_at)}
                )
                run.status = 'ABANDONED'
                run.completed_at = timezone.now()
                run.save()
                count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'  Error for run {run.pk}: {e}'))

        self.stdout.write(self.style.SUCCESS(f'Penalized {count} abandoned flows ({count * 20} total points).'))
