from django.core.management.base import BaseCommand

from api_v1.mdy_plate_order_sync import sync_mdy_plate_orders_to_staging


class Command(BaseCommand):
    help = '同步明道云开版数据表到暂存表（可选抓取跨表关联数据）'

    def add_arguments(self, parser):
        parser.add_argument('--page-size', type=int, default=100)
        parser.add_argument('--max-pages', type=int, default=None)
        parser.add_argument('--max-records', type=int, default=None)

        # 默认抓取关联表数据；如需关闭可显式传 --without-related
        parser.add_argument('--with-related', dest='with_related', action='store_true', default=True)
        parser.add_argument('--without-related', dest='with_related', action='store_false')

        parser.add_argument('--max-related-per-type', type=int, default=5)
        parser.add_argument(
            '--request-interval-seconds',
            type=float,
            default=0.02,
            help='每次明道云请求之间的最小间隔（用于限流，50qps 建议 >= 0.02）',
        )
        parser.add_argument(
            '--sort-direction',
            choices=['asc', 'desc'],
            default='asc',
            help='按 ctime 升序（asc）或降序（desc）抓取',
        )
        parser.add_argument(
            '--use-checkpoint',
            dest='use_checkpoint',
            action='store_true',
            default=True,
            help='读取 DataSync 游标（默认开启）',
        )
        parser.add_argument(
            '--skip-checkpoint',
            dest='use_checkpoint',
            action='store_false',
            help='忽略 DataSync 游标，从第一页开始',
        )
        parser.add_argument(
            '--update-checkpoint',
            dest='update_checkpoint',
            action='store_true',
            default=True,
            help='同步完成后写入 DataSync 记录（默认开启）',
        )
        parser.add_argument(
            '--skip-checkpoint-write',
            dest='update_checkpoint',
            action='store_false',
            help='本次同步不写入 DataSync 记录',
        )

    def handle(self, *args, **options):
        payload = sync_mdy_plate_orders_to_staging(
            page_size=options['page_size'],
            max_pages=options['max_pages'],
            max_records=options['max_records'],
            with_related=options['with_related'],
            max_related_per_type=options['max_related_per_type'],
            request_interval_seconds=options['request_interval_seconds'],
            use_checkpoint=options['use_checkpoint'],
            update_checkpoint=options['update_checkpoint'],
            sort_direction=options['sort_direction'],
        )
        self.stdout.write(self.style.SUCCESS(str(payload)))
