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

from market.dev_seed import DemoMarketplaceSeeder, SeedOptions


class Command(BaseCommand):
    help = (
        "Seed the marketplace with realistic DEV-ONLY demo data for mobile and API testing. "
        "Generates users, categories, products, listings, offers, and ratings. "
        "This command never runs automatically and refuses to run outside DEBUG unless --force is used."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "--reset-demo",
            action="store_true",
            help="Delete demo-tagged marketplace seed data before rebuilding it.",
        )
        parser.add_argument(
            "--force",
            action="store_true",
            help="Allow this DEV-ONLY seed command to run even when DEBUG is False.",
        )
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Show what would be seeded without making changes.",
        )
        parser.add_argument(
            "--count",
            type=float,
            default=None,
            help="Scale factor for all counts (e.g., --count 0.5 for half, --count 2 for double).",
        )
        parser.add_argument("--admins", type=int, default=2, help="Target admin/support accounts.")
        parser.add_argument("--sellers", type=int, default=10, help="Target seller accounts.")
        parser.add_argument("--buyers", type=int, default=30, help="Target buyer accounts.")
        parser.add_argument("--farmers", type=int, default=20, help="Target farmer accounts.")
        parser.add_argument(
            "--field-officers",
            type=int,
            default=5,
            dest="field_officers",
            help="Target field officer accounts.",
        )
        parser.add_argument("--categories", type=int, default=8, help="Target marketplace categories.")
        parser.add_argument("--products", type=int, default=150, help="Target approved market products.")
        parser.add_argument("--listings", type=int, default=50, help="Target live farmer listings.")
        parser.add_argument("--orders", type=int, default=15, help="Target sample orders.")
        parser.add_argument("--offers", type=int, default=30, help="Target sample listing offers.")
        parser.add_argument(
            "--no-ratings",
            action="store_false",
            dest="ratings",
            help="Skip generating ratings and feedback.",
        )

    def handle(self, *args, **options):
        if not settings.DEBUG and not options["force"]:
            raise CommandError(
                "seed_marketplace_demo is DEV-ONLY. Run it only with DEBUG=True, or pass --force deliberately outside DEBUG."
            )

        # Apply count scaling if provided
        count_scale = options.get("count")
        if count_scale is not None and count_scale <= 0:
            raise CommandError("--count must be a positive number.")

        numeric_fields = [
            "admins",
            "sellers",
            "buyers",
            "farmers",
            "field_officers",
            "categories",
            "products",
            "listings",
            "orders",
            "offers",
        ]

        # Scale all counts if provided
        if count_scale is not None:
            self.stdout.write(self.style.WARNING(f"\n📊 Applying {count_scale}x scaling to target counts:\n"))
            for field_name in numeric_fields:
                original_value = int(options[field_name] or 0)
                scaled_value = max(1, round(original_value * count_scale))
                # Show scaling details
                display_name = field_name.replace("_", " ").title()
                self.stdout.write(f"  {display_name}: {original_value} → {scaled_value}")
                options[field_name] = scaled_value
            self.stdout.write("")

        for field_name in numeric_fields:
            if int(options[field_name] or 0) < 0:
                raise CommandError(f"{field_name.replace('_', ' ')} cannot be negative.")

        dry_run = options.get("dry_run", False)
        self.stdout.write(
            self.style.WARNING(
                "Running DEV-ONLY marketplace seeding. "
                "This command is idempotent for demo identities and never runs automatically."
            )
        )
        
        if dry_run:
            self.stdout.write(self.style.ERROR("🔍 DRY RUN MODE - No data will be saved\n"))

        seeder = DemoMarketplaceSeeder(
            options=SeedOptions(
                admins=options["admins"],
                sellers=options["sellers"],
                buyers=options["buyers"],
                farmers=options["farmers"],
                field_officers=options["field_officers"],
                categories=options["categories"],
                products=options["products"],
                listings=options["listings"],
                orders=options["orders"],
                offers=options["offers"],
                ratings=options.get("ratings", True),
                reset_demo=options["reset_demo"],
                dry_run=dry_run,
            ),
            printer=lambda message: self.stdout.write(message),
        )

        result = seeder.run()
        summary = result["summary"]
        counts = result["catalog_counts"]
        reused_accounts = result["reused_accounts"]

        self.stdout.write(self.style.SUCCESS("\n✅ Marketplace demo seed complete!\n"))
        self.stdout.write(
            f"📊 Seeded totals:\n"
            f"   - {counts['categories']} categories\n"
            f"   - {counts['products']} products\n"
            f"   - {counts['listings']} farmer listings\n"
            f"   - {counts['buyers']} buyers\n"
            f"   - {counts['sellers']} sellers\n"
            f"   - {counts['farmers']} farmers\n"
            f"   - {counts['field_officers']} field officers\n"
            f"   - {counts['admins']} admins\n"
        )

        self.stdout.write("📋 Creation/update summary:")
        for key in sorted(summary):
            self.stdout.write(f"  • {key}: {summary[key]}")

        self.stdout.write("\n🔑 Demo credentials:")
        self.stdout.write("  Password (all accounts): DemoPass123!")
        for role_name, records in result["demo_credentials"].items():
            if not records:
                continue
            self.stdout.write(f"\n  {role_name.replace('_', ' ').title()}:")
            for record in records:
                self.stdout.write(
                    f"    • {record['email']} | {record['phone_number']}"
                )

        if reused_accounts and any(reused_accounts.values()):
            self.stdout.write("\n♻️  Reused existing accounts (passwords not changed):")
            for role_name, records in reused_accounts.items():
                if not records:
                    continue
                self.stdout.write(f"  {role_name.replace('_', ' ').title()}:")
                for record in records:
                    label = record["email"] or record["phone_number"] or record["full_name"] or "User"
                    self.stdout.write(f"    • {label}")

        self.stdout.write("\n🏷️  Demo identity markers:")
        self.stdout.write(f"  • Email domain: @{result['demo_identifiers']['email_domain']}")
        self.stdout.write(f"  • Product SKU prefix: {result['demo_identifiers']['product_sku_prefix']}")
        self.stdout.write(f"  • Listing slug prefix: {result['demo_identifiers']['listing_slug_prefix']}")
        
        self.stdout.write(
            self.style.WARNING(
                "\n💡 Tip: Reruns reuse and update demo identities. "
                "Use --reset-demo to remove and rebuild all demo data cleanly.\n"
            )
        )
