# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/004_CLI.ipynb.

# %% auto 0
__all__ = ['ImportFromStringError', 'run', 'generate_docs']

# %% ../nbs/004_CLI.ipynb 1
import importlib
import sys
from asyncio import run as aiorun
from pathlib import Path
from typing import *

from fastapi import FastAPI
import typer

from .application import FastKafkaAPI

# %% ../nbs/004_CLI.ipynb 6
class ImportFromStringError(Exception):
    pass


def _import_from_string(import_str: str) -> Any:
    """Imports library from string

    Note:
        copied from https://github.com/encode/uvicorn/blob/master/uvicorn/importer.py

    Args:
        import_str: input string in form 'main:app'

    """
    sys.path.append(".")

    if not isinstance(import_str, str):
        return import_str

    module_str, _, attrs_str = import_str.partition(":")
    if not module_str or not attrs_str:
        message = (
            'Import string "{import_str}" must be in format "<module>:<attribute>".'
        )
        typer.secho(f"{message}", err=True, fg=typer.colors.RED)
        raise ImportFromStringError(message.format(import_str=import_str))

    try:
        # nosemgrep: python.lang.security.audit.non-literal-import.non-literal-import
        module = importlib.import_module(module_str)
    except ImportError as exc:
        if exc.name != module_str:
            raise exc from None
        message = 'Could not import module "{module_str}".'
        raise ImportFromStringError(message.format(module_str=module_str))

    instance = module
    try:
        for attr_str in attrs_str.split("."):
            instance = getattr(instance, attr_str)
    except AttributeError:
        message = 'Attribute "{attrs_str}" not found in module "{module_str}".'
        raise ImportFromStringError(
            message.format(attrs_str=attrs_str, module_str=module_str)
        )

    return instance

# %% ../nbs/004_CLI.ipynb 9
_app = typer.Typer(help="")


@_app.command(
    help="Runs Fast Kafka API application using uvicorn",
)
def run(root_path: str = typer.Option(".", help="")) -> None:
    try:
        raise NotImplementedError()
    except Exception as e:
        typer.secho(f"Unexpected internal error: {e}", err=True, fg=typer.colors.RED)
        raise typer.Exit(1)


@_app.command(
    help="Creates documentation for a Fast Kafka API application ",
)
def generate_docs(
    root_path: str = typer.Option(
        ".", help="root path under which documentation will be create"
    ),
    app: str = typer.Argument(
        ...,
        help="input in the form of 'path:app', where **path** is the path to a python file and **app** is an object of type **FastKafkaAPI**.",
    ),
) -> None:
    try:
        application = _import_from_string(app)
        application.generate_async_spec()
    except Exception as e:

        typer.secho(f"Unexpected internal error: {e}", err=True, fg=typer.colors.RED)
        raise typer.Exit(1)
