from django.core.management.base import BaseCommand
from django.utils import timezone

from apps.inventory.services import DeadstockService


class Command(BaseCommand):
    help = "Recompute deadstock scores and tiers for all IN_STOCK items."

    def add_arguments(self, parser):
        parser.add_argument(
            "--business-id",
            type=str,
            default=None,
            help="Limit recompute to a single business UUID.",
        )

    def handle(self, *args, **options):
        from apps.business.models import Business  

        business_id = options["business_id"]

        if business_id:
            businesses = Business.objects.filter(id=business_id, is_active=True)
        else:
            businesses = Business.objects.filter(is_active=True)

        total_updated = 0
        start = timezone.now()

        for business in businesses:
            self.stdout.write(f"Processing: {business.name} ({business.id}) ...")
            try:
                count = DeadstockService.compute_and_save_all(business=business)
                total_updated += count
                self.stdout.write(
                    self.style.SUCCESS(f"  ✓ {count} items updated")
                )
            except Exception as exc:
                self.stderr.write(
                    self.style.ERROR(f"  ✗ Error for {business.id}: {exc}")
                )

        elapsed = (timezone.now() - start).total_seconds()
        self.stdout.write(
            self.style.SUCCESS(
                f"\\nDone. {total_updated} total items updated in {elapsed:.1f}s."
            )
        )