#!python
# *****************************************************************************
# Copyright (c) 2024 IBM Corporation and other Contributors.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# *****************************************************************************

import logging
from sys import argv

from mas.cli import __version__ as VERSION
from mas.cli.install.app import InstallApp
from mas.cli.aiservice.install.app import AiServiceInstallApp
from mas.cli.aiservice.upgrade.app import AiServiceUpgradeApp
from mas.cli.update.app import UpdateApp
from mas.cli.upgrade.app import UpgradeApp
from mas.cli.uninstall.app import UninstallApp
from mas.cli.backup.app import BackupApp
from mas.cli.restore.app import RestoreApp
from mas.cli.mirror.app import MirrorApp
from mas.cli.setup_rbac.app import SetupRBACApp
from mas.cli.pre_install.app import SetupPreinstallRBACApp

from prompt_toolkit import HTML, print_formatted_text
from urllib3.exceptions import MaxRetryError
from jinja2.exceptions import TemplateNotFound
from kubeconfig.exceptions import KubectlCommandError
from kubernetes.client.exceptions import ApiException

logger = logging.getLogger(__name__)


def usage():
    print_formatted_text(HTML(""))

    print_formatted_text(HTML(f"\n<u>IBM Maximo Application Suite Admin CLI v{VERSION}</u>"))
    print_formatted_text(
        HTML(
            "Powered by <DarkGoldenRod><u>https://github.com/ibm-mas/ansible-devops/</u></DarkGoldenRod> and <DarkGoldenRod><u>https://tekton.dev/</u></DarkGoldenRod>"
        )
    )
    print("")
    print_formatted_text(
        HTML(
            "Important Notice:\nThis standalone CLI (<ForestGreen>mas-cli</ForestGreen>) is still in beta state, not all functions supported by the <ForestGreen>mas</ForestGreen> function in quay.io/ibmmas/cli are supported yet"
        )
    )
    print("")
    print_formatted_text(
        HTML(
            "<b>MAS Management Actions:</b>\n"
            + " - <ForestGreen>mas-cli install</ForestGreen>   Install IBM Maximo Application Suite\n"  # noqa: W503
            + " - <ForestGreen>mas-cli update</ForestGreen>    Apply updates and security fixes\n"  # noqa: W503
            + " - <ForestGreen>mas-cli upgrade</ForestGreen>   Upgrade to a new MAS release\n"  # noqa: W503
            + " - <ForestGreen>mas-cli backup</ForestGreen>    Backup a MAS instance\n"  # noqa: W503
            + " - <ForestGreen>mas-cli uninstall</ForestGreen> Remove MAS from the cluster\n"  # noqa: W503
            + " - <ForestGreen>mas-cli mirror</ForestGreen>    Mirror container images \n"  # noqa: W503
            + " - <ForestGreen>mas-cli setup-rbac</ForestGreen>  Set up RBAC resources for MAS installation\n"  # noqa: W503
            + " - <ForestGreen>mas-cli pre-install</ForestGreen>  Set up pre-install RBAC for MAS\n"  # noqa: W503
        )
    )
    print_formatted_text(HTML("For usage information run <ForestGreen>mas-cli [action] --help</ForestGreen>\n"))


if __name__ == "__main__":
    app = None
    try:
        function = argv[1]

        if function == "install":
            app = InstallApp()
            exit(app.install(argv[2:]))
        elif function == "aiservice-install":
            app = AiServiceInstallApp()
            exit(app.install(argv[2:]))
        elif function == "aiservice-upgrade":
            app = AiServiceUpgradeApp()
            exit(app.upgrade(argv[2:]))
        elif function == "uninstall":
            app = UninstallApp()
            exit(app.uninstall(argv[2:]))
        elif function == "update":
            app = UpdateApp()
            exit(app.update(argv[2:]))
        elif function == "upgrade":
            app = UpgradeApp()
            app.upgrade(argv[2:])
        elif function == "backup":
            app = BackupApp()
            app.backup(argv[2:])
        elif function == "restore":
            app = RestoreApp()
            app.restore(argv[2:])
        elif function == "mirror":
            app = MirrorApp()
            app.mirror(argv[2:])
        elif function == "setup-rbac":
            app = SetupRBACApp()
            app.setupRBAC(argv[2:])
        elif function == "pre-install":
            app = SetupPreinstallRBACApp()
            app.setupPreinstallRBAC(argv[2:])
        elif function in ["-h", "--help"]:
            usage()
            exit(0)
        else:
            usage()
            print_formatted_text(HTML(f"<Red>Unknown action: {function}</Red>\n"))
            exit(1)

    except KeyboardInterrupt:
        pass
    except ApiException as e:
        error_msg = f"[{e.status}:{e.reason}] {e.body if hasattr(e, 'body') else str(e)}"
        if app:
            app.fatalError(message=error_msg)
        else:
            logger.error(error_msg)
            exit(1)
    except MaxRetryError as e:
        if app:
            app.fatalError(message="Unable to connect to API server", exception=e)
        else:
            logger.error("Unable to connect to API server", exc_info=e)
            exit(1)
    except TemplateNotFound as e:
        if app:
            app.fatalError("Could not find template", exception=e)
        else:
            logger.error("Could not find template", exc_info=e)
            exit(1)
    except KubectlCommandError as e:
        if app:
            app.fatalError("Could not execute kubectl command", exception=e)
        else:
            logger.error("Could not execute kubectl command", exc_info=e)
            exit(1)
