import logging
import random
import string

import click
from caprover_api import caprover_api
from environs import Env

logging.basicConfig(level=logging.DEBUG)


def generate_random_string(length):
    base_characters = string.ascii_letters + string.digits
    random_string = "".join(random.choice(base_characters) for _ in range(length))
    return random_string


@click.command()
@click.option(
    "-a",
    "--app-name",
    required=True,
    help="app name to deploy should start with vbv-feature-, use slugified branch name",
)
@click.option(
    "-i",
    "--image-name",
    default=None,
    help="docker image name to deploy (like docker.io/iterativ/vbv-lernwelt-django)",
)
@click.option(
    "-e",
    "--environment-file",
    default=None,
    help="path to environment file to use for deployment (like ./env_secrets/caprover_feature.env)",
)
def main(app_name, image_name, environment_file):
    env = Env()

    if environment_file is not None:
        env.read_env(environment_file, recurse=False, override=True)

    cap = caprover_api.CaproverAPI(
        dashboard_url=env.str("CAPROVER_DOMAIN"),
        password=env.str("CAPROVER_PASSWORD"),
    )

    db_pass = env.str("POSTGRES_PASSWORD", generate_random_string(63))
    db_user = env.str("POSTGRES_USER", "postgres")
    db_name = env.str("POSTGRES_DB", "vbv_lernwelt")

    cap.deploy_one_click_app(
        one_click_app_name="postgres",
        namespace=app_name,
        # check https://github.com/caprover/one-click-apps/blob/master/public/v4/apps/postgres.yml
        app_variables={
            "$$cap_postgres_version": "14.2",
            "$$cap_pg_user": db_user,
            "$$cap_pg_pass": db_pass,
            "$$cap_pg_db": db_name,
        },
        automated=True,
    )

    default_allowed_hosts = f"{app_name}.iterativ.ch,{app_name}.control.iterativ.ch"

    cap.create_and_update_app(
        app_name=app_name,
        enable_ssl=True,
        force_ssl=True,
        expose_as_web_app=True,
        image_name=image_name,
        container_http_port=7555,
        environment_variables={
            "IT_APP_ENVIRONMENT": env.str("IT_APP_ENVIRONMENT", "dev-feature"),
            "IT_DEFAULT_ADMIN_PASSWORD": env.str(
                "IT_DEFAULT_ADMIN_PASSWORD", "ACEEs0DCmNaPxdoNV8vhccuCTRl9b"
            ),
            "POSTGRES_HOST": f"srv-captain--{app_name}-postgres",
            "POSTGRES_PORT": 5432,
            "POSTGRES_DB": db_name,
            "POSTGRES_USER": db_user,
            "POSTGRES_PASSWORD": db_pass,
            "IT_DJANGO_ALLOWED_HOSTS": env.str(
                "IT_DJANGO_ALLOWED_HOSTS", default_allowed_hosts
            ),
            "IT_DJANGO_SECRET_KEY": env.str(
                "IT_DJANGO_SECRET_KEY", generate_random_string(63)
            ),
            "IT_DJANGO_DEBUG": "false",
            "IT_SERVE_VUE": "false",
            "IT_ALLOW_LOCAL_LOGIN": "true",
            "IT_DJANGO_LOGGING_CONF": "IT_DJANGO_LOGGING_CONF_JSON_FILE",
        },
    )


if __name__ == "__main__":
    main()
