"""
Export Edge Manifest

Generates the static JSON manifest that Mizan Edge reads at deploy time
to configure CDN cache rules and invalidation routing.

Usage:
    python manage.py export_edge_manifest
    python manage.py export_edge_manifest --output mizan-manifest.json
    python manage.py export_edge_manifest --base-url /api/mizan
"""

import json
from pathlib import Path

from django.core.management.base import BaseCommand

from mizan.export import generate_edge_manifest


class Command(BaseCommand):
    help = "Export Edge manifest for CDN cache invalidation"

    def add_arguments(self, parser):
        parser.add_argument(
            "--output",
            "-o",
            type=str,
            default=None,
            help="Output file path. If not specified, outputs to stdout.",
        )
        parser.add_argument(
            "--indent",
            type=int,
            default=2,
            help="JSON indentation level (0 for compact output)",
        )
        parser.add_argument(
            "--base-url",
            type=str,
            default="/api/mizan",
            help="Mizan API mount point (default: /api/mizan)",
        )

    def handle(self, *args, **options):
        manifest = generate_edge_manifest(base_url=options["base_url"])
        indent = options["indent"] if options["indent"] > 0 else None
        json_output = json.dumps(manifest, indent=indent, sort_keys=True)

        if options["output"]:
            output_path = Path(options["output"])
            output_path.parent.mkdir(parents=True, exist_ok=True)
            output_path.write_text(json_output)
            self.stdout.write(self.style.SUCCESS(f"Manifest written to {output_path}"))
        else:
            self.stdout.write(json_output)
