from django.core.management.base import BaseCommand, CommandError
from api_v1.tasks import (
    retry_external_printing_sync_failures_impl,
)


class Command(BaseCommand):
    help = '基于失败记录重试外部印染 records 同步'

    def add_arguments(self, parser):
        parser.add_argument('--limit', type=int, default=None, help='最多重试多少条失败记录；不传则重试全部')
        parser.add_argument(
            '--run-date',
            type=str,
            default=None,
            help='仅重试指定任务日期的失败记录，格式 YYYY-MM-DD',
        )
        parser.add_argument(
            '--record-id',
            action='append',
            type=int,
            default=None,
            help='仅重试指定 external_record_id，可多次传入',
        )

    def handle(self, *args, **options):
        limit = options.get('limit')
        run_date_text = options.get('run_date')
        record_ids = options.get('record_id') or []
        try:
            result = retry_external_printing_sync_failures_impl(
                limit=limit,
                run_date_text=run_date_text,
                record_ids=record_ids,
            )
        except ValueError as exc:
            raise CommandError(f'--run-date 格式非法: {run_date_text}') from exc
        self.stdout.write(self.style.SUCCESS(str(result)))
