"""
Export mizan Schema

Management command to export the mizan OpenAPI schema for TypeScript code generation.
The schema is consumed by openapi-typescript for robust type generation.

Usage:
    python manage.py export_mizan_schema                    # Output to stdout
    python manage.py export_mizan_schema --output schema.json  # Output to file
"""

import json
from pathlib import Path

from django.core.management.base import BaseCommand

from mizan.export import generate_openapi_schema


class Command(BaseCommand):
    help = "Export mizan OpenAPI schema for TypeScript code generation"

    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)",
        )

    def handle(self, *args, **options):
        schema = generate_openapi_schema()
        indent = options["indent"] if options["indent"] > 0 else None
        json_output = json.dumps(schema, indent=indent)

        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"Schema written to {output_path}"))
        else:
            self.stdout.write(json_output)
