import json
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from apps.inventory.control_queries import inventory_anomalies
from apps.inventory.queries import authorized_locations


class Command(BaseCommand):
    help = "Read-only inventory reconciliation within an actor's authorized inventory scope."

    def add_arguments(self, parser):
        parser.add_argument("--actor", required=True, help="Existing active username with inventory view scope")

    def handle(self, *args, **options):
        actor = get_user_model().objects.filter(username=options["actor"], is_active=True).first()
        if actor is None or not authorized_locations(actor=actor).exists():
            raise CommandError("An active actor with visible inventory locations is required.")
        findings = {name: list(rows.values_list("pk", flat=True)) for name, rows in inventory_anomalies(actor=actor).items()}
        self.stdout.write(json.dumps(findings, default=str, sort_keys=True))
        if any(findings.values()):
            raise CommandError("Inventory anomalies found. No records were changed.")
