"""__init__.py module for the REST API plugin."""

# WARNING - DO NOT EDIT - YOUR CHANGES WILL NOT BE PROTECTED.
# This file is auto-generated by the aac gen-plugin and may be overwritten.

from os.path import join, dirname

from aac.context.language_context import LanguageContext
from aac.execute import hookimpl
from aac.execute.aac_execution_result import ExecutionResult, ExecutionStatus
from aac.execute.plugin_runner import PluginRunner

from rest_api.rest_api_impl import plugin_name, rest_api, gen_openapi_spec


rest_api_aac_file_name = "rest_api.aac"


def run_rest_api(host: str = "0.0.0.0", port: int = 8000) -> ExecutionResult:
    """
    Start a RESTful interface for interacting with and managing AaC.

    Args:
        host (str): Set the hostname of the service. Useful for operating behind proxies.
        port (int): The port to which the RESTful service will be bound.

    Returns:
         The results of the execution of the plugin rest-api command.
    """

    result = ExecutionResult(plugin_name, "rest-api", ExecutionStatus.SUCCESS, [])

    rest_api_result = rest_api(host, port)
    if not rest_api_result.is_success():
        return rest_api_result
    else:
        result.add_messages(rest_api_result.messages)

    return result


def run_gen_openapi_spec(output_directory: str) -> ExecutionResult:
    """
    Write the OpenAPI schema to a JSON file.

    Args:
         output_directory (str): The output directory in which to write the AaC OpenAPI JSON file.

    Returns:
         The results of the execution of the plugin gen-openapi-spec command.
    """

    result = ExecutionResult(
        plugin_name, "gen-openapi-spec", ExecutionStatus.SUCCESS, []
    )

    gen_openapi_spec_result = gen_openapi_spec(output_directory)
    if not gen_openapi_spec_result.is_success():
        return gen_openapi_spec_result
    else:
        result.add_messages(gen_openapi_spec_result.messages)

    return result


@hookimpl
def register_plugin() -> None:
    """
    Registers information about the plugin for use in the CLI.
    """

    active_context = LanguageContext()
    rest_api_aac_file = join(dirname(__file__), rest_api_aac_file_name)
    definitions = active_context.parse_and_load(rest_api_aac_file)

    rest_api_plugin_definition = [
        definition for definition in definitions if definition.name == plugin_name
    ][0]

    plugin_instance = rest_api_plugin_definition.instance
    for file_to_load in plugin_instance.definition_sources:
        active_context.parse_and_load(file_to_load)

    plugin_runner = PluginRunner(plugin_definition=rest_api_plugin_definition)
    plugin_runner.add_command_callback("rest-api", run_rest_api)
    plugin_runner.add_command_callback("gen-openapi-spec", run_gen_openapi_spec)

    active_context.register_plugin_runner(plugin_runner)
