import argparse
import asyncio
import logging

import carb
import omni.kit.app
import omni.kit.documentation.builder

logger = logging.getLogger(__name__)


_app_ready_sub = None


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "ext_id",
        help="Extension id (name-version).",
    )
    parser.add_argument(
        "output_path",
        help="Path to output generated files to.",
    )

    options = parser.parse_args()

    async def _generate_and_exit(options):
        # Skip 2 updates to make sure all extensions loaded and initialized
        await omni.kit.app.get_app().next_update_async()
        await omni.kit.app.get_app().next_update_async()

        try:
            result = omni.kit.documentation.builder.generate_for_sphinx(options.ext_id, options.output_path)
        except Exception as e:  # pylint: disable=broad-except
            carb.log_error(f"Failed to generate docs for sphinx: {e}")

        for _ in range(5):
            await omni.kit.app.get_app().next_update_async()

        returncode = 0 if result else 33
        omni.kit.app.get_app().post_quit(returncode)

    def on_app_ready(e):
        global _app_ready_sub
        _app_ready_sub = None
        asyncio.ensure_future(_generate_and_exit(options))

    app = omni.kit.app.get_app()
    if app.is_app_ready():
        on_app_ready(None)
    else:
        global _app_ready_sub
        _app_ready_sub = app.get_startup_event_stream().create_subscription_to_pop_by_type(
            omni.kit.app.EVENT_APP_READY, on_app_ready, name="omni.kit.documentation.builder generate_docs_for_sphinx"
        )


if __name__ == "__main__":
    main()
