import json

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

from api.services.integration.bootstrap import (
    ResourceBootstrapSafetyError,
    revise_resource_projection_snapshots,
)


class Command(BaseCommand):
    help = (
        "Re-emit all existing Staff and Locations exactly once for an explicit "
        "Resource Booking projection-contract revision."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "--confirm-resource-projection-revision", action="store_true"
        )
        parser.add_argument("--operation-key")
        parser.add_argument("--batch-size", type=int, default=100)
        parser.add_argument("--actor-id", type=int)

    def handle(self, *args, **options):
        if not options["confirm_resource_projection_revision"]:
            raise CommandError("--confirm-resource-projection-revision is required")
        try:
            summary = revise_resource_projection_snapshots(
                operation_key=options["operation_key"],
                batch_size=options["batch_size"],
                actor_id=options["actor_id"],
            )
        except (ResourceBootstrapSafetyError, ValueError) as error:
            raise CommandError(str(error)) from error
        result = summary.as_dict()
        result["operation"] = "resource_projection_revision"
        result["operation_key"] = options["operation_key"]
        self.stdout.write(json.dumps(result, sort_keys=True))
