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

from market.services.product_image_enrichment import (
    MarketProductImageEnricher,
    ProductImageEnrichmentOptions,
)


class Command(BaseCommand):
    help = (
        "Download and attach testing/demo-friendly images to market products using the "
        "current MarketProductImage gallery model. This command is explicit only, never auto-runs, "
        "and defaults to filling products that are missing images."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Search and report matches without downloading or attaching any image files.",
        )
        parser.add_argument(
            "--limit",
            type=int,
            default=None,
            help="Maximum number of matching products to process in this run.",
        )
        parser.add_argument(
            "--category",
            type=str,
            default="",
            help="Optional category name or slug filter, for example 'Fresh Produce'.",
        )
        parser.add_argument(
            "--only-missing",
            action="store_true",
            help="Explicitly restrict the run to products that have no images. This is also the default behavior.",
        )
        parser.add_argument(
            "--replace-existing",
            action="store_true",
            help="Replace the current product gallery with one newly fetched primary image.",
        )

    def handle(self, *args, **options):
        limit = options.get("limit")
        if limit is not None and int(limit) <= 0:
            raise CommandError("--limit must be a positive integer.")

        if options["replace_existing"] and options["only_missing"]:
            raise CommandError(
                "Use either the default/--only-missing mode or --replace-existing, not both together."
            )

        only_missing = True if not options["replace_existing"] else False
        if options["only_missing"]:
            only_missing = True

        self.stdout.write(
            self.style.WARNING(
                "Testing/demo image enrichment only. "
                "The command downloads candidate images into local media storage and never hotlinks remote URLs."
            )
        )
        self.stdout.write(
            "Source strategy: Wikimedia Commons API search in file namespace, "
            "downloaded locally and attached through MarketProductImage so the existing WEBP conversion remains in charge."
        )

        enricher = MarketProductImageEnricher(
            options=ProductImageEnrichmentOptions(
                dry_run=bool(options["dry_run"]),
                limit=limit,
                category=str(options["category"] or "").strip(),
                only_missing=only_missing,
                replace_existing=bool(options["replace_existing"]),
                verbosity=int(options.get("verbosity", 1) or 1),
            ),
            printer=lambda message: self.stdout.write(message),
        )

        summary = enricher.run()

        self.stdout.write("")
        self.stdout.write(self.style.SUCCESS("Market product image enrichment complete."))
        self.stdout.write(f"Products considered: {summary['products_considered']}")
        self.stdout.write(f"Products scanned: {summary['products_scanned']}")
        self.stdout.write(f"Images attached: {summary['images_attached']}")
        self.stdout.write(f"Images replaced: {summary['images_replaced']}")
        self.stdout.write(f"Already had images: {summary['already_had_images']}")
        self.stdout.write(f"Skipped: {summary['skipped']}")
        self.stdout.write(f"Not found: {summary['not_found']}")
        self.stdout.write(f"Failed: {summary['failed']}")
        if options["dry_run"]:
            self.stdout.write(f"Dry-run matches: {summary['dry_run_matches']}")

        if not options["dry_run"] and not options["replace_existing"]:
            self.stdout.write(
                self.style.WARNING(
                    "Default reruns remain safe: products that already have images are left untouched unless --replace-existing is passed."
                )
            )
