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

from api_v1.external_product_image_backfill import run_external_product_image_backfill
from api_v1.tasks import _fetch_external_product_image, _upload_product_image


class Command(BaseCommand):
    help = '为来自外部印染订单的生产子单所关联且 image 为空的 Product 通过 external_raw.YanSe 回补图片'

    def add_arguments(self, parser):
        parser.add_argument('--merchant-id', type=int, help='仅处理指定商户的产品')
        parser.add_argument('--product-id', type=int, help='仅处理指定产品')
        parser.add_argument('--limit', type=int, help='最多处理多少条符合条件的产品')
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='仅输出将处理的产品，不实际请求外部 API 或写库',
        )

    def handle(self, *args, **options):
        merchant_id = options.get('merchant_id')
        product_id = options.get('product_id')
        limit = options.get('limit')
        if limit is not None:
            if int(limit) <= 0:
                raise CommandError('--limit 必须大于 0')
            limit = int(limit)

        payload = run_external_product_image_backfill(
            fetch_image=_fetch_external_product_image,
            upload_image=_upload_product_image,
            merchant_id=merchant_id,
            product_id=product_id,
            limit=limit,
            dry_run=bool(options.get('dry_run')),
            on_success=lambda message: self.stdout.write(self.style.SUCCESS(message)),
            on_error=lambda message: self.stderr.write(self.style.ERROR(message)),
            on_info=lambda message: self.stdout.write(message),
        )

        self.stdout.write(self.style.SUCCESS(f'完成: {payload}'))
