"""
Schema-export CLI for codegen consumption.

Usage:
    python -m mizan_fastapi.cli <module>

Imports the named module (whose import side effects must register every
@client function with mizan_core.registry — typically by `@client` plus
`register(...)` calls at module top level), then prints the OpenAPI
schema to stdout as JSON.

Mirrors mizan-django's `manage.py export_mizan_schema` so the codegen
CLI can fetch from either backend the same subprocess way.
"""

from __future__ import annotations

import importlib
import json
import sys

from .schema import build_schema


def main(argv: list[str] | None = None) -> int:
    args = list(sys.argv[1:] if argv is None else argv)
    if len(args) != 1:
        print("usage: python -m mizan_fastapi.cli <module>", file=sys.stderr)
        return 2

    module_name = args[0]
    try:
        importlib.import_module(module_name)
    except Exception as e:
        print(f"failed to import {module_name!r}: {e}", file=sys.stderr)
        return 1

    schema = build_schema()
    json.dump(schema, sys.stdout)
    sys.stdout.write("\n")
    return 0


if __name__ == "__main__":
    sys.exit(main())
