import traceback

import click
from rich import print
from rich.prompt import Prompt

import coiled

from ..utils import CONTEXT_SETTINGS
from .util import setup_failure


@click.command(context_settings=CONTEXT_SETTINGS)
def setup_wizard() -> bool:
    return do_setup_wizard()


def do_setup_wizard() -> bool:
    coiled.utils.login_if_required()

    coiled.add_interaction(
        action="cli-setup-wizard:start",
        success=True,
    )

    print(
        "Welcome to Coiled!\n\n"
        "To begin we need to connect Coiled to your cloud account.\n"
        "Select one of the following options:\n\n"
        "  1. Amazon Web Service (AWS)\n"
        "  2. Google Cloud Platform (GCP)\n"
        "  3. I don't have a cloud account, set me up with a free trial?\n"
        "  [red]x[/red]. Exit setup\n"
    )

    try:
        choice = Prompt.ask(
            "Choice",
            choices=["1", "2", "3", "x"],
            show_choices=False,
        )
    except KeyboardInterrupt:
        coiled.add_interaction(action="cli-setup-wizard:KeyboardInterrupt", success=False)
        return False

    coiled.add_interaction(action="cli-setup-wizard:prompt", success=True, choice=choice)

    if choice == "1":  # AWS
        print("\nRunning [green]coiled setup aws[/green]\n")
        from .aws import do_setup

        try:
            return do_setup(slug="coiled")
        except Exception:
            setup_failure(f"Exception raised {traceback.format_exc()}", backend="aws")
            raise
    elif choice == "2":  # GCP
        print("\nRunning [green]coiled setup gcp[/green]\n")
        from .gcp import do_setup

        try:
            return do_setup()
        except Exception:
            setup_failure(f"Exception raised {traceback.format_exc()}", backend="gcp")
            raise
    elif choice == "3":  # Other
        print(
            "\nCoiled currently supports Amazon Web Service and Google Cloud."
            "It's easy to make an account with either and get "
            "started using Coiled. Please see our documentation about choosing a cloud provider:\n"
            "[link]https://docs.coiled.io/user_guide/backends.html#need-a-cloud-provider-account[/link]\n\n"
            "If you're not ready to create your own cloud provider account, "
            "but would still like to try Coiled, we can set you up with a trial on our account. "
            "Reach out to us at "
            "[link=mailto:hello@coiled.io?subject=Trial%20Account]hello@coiled.io[/link] "
            "with a brief note about how you're using Dask."
        )

    return False
