import logging
import sys

from environs import Env

# TODO: I use a locally patched caprover api for now
sys.path.append(r'/Users/daniel/workspace/iterativ-caprover/Caprover-API')
from caprover_api import caprover_api


logging.basicConfig(level=logging.DEBUG)


env = Env()
env.read_env("./env_secrets/caprover_stage.env", recurse=False, override=True)
app_name = "myvbv-stage"

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

db_pass = env.str('POSTGRES_PASSWORD')
db_user = env.str('POSTGRES_USER')
db_name = env.str('POSTGRES_DB')

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
)

cap.create_and_update_app(
    app_name=app_name,
    enable_ssl=True,
    force_ssl=True,
    expose_as_web_app=True,
    image_name='docker.io/iterativ/vbv-lernwelt-django',
    environment_variables={
        # 'DJANGO_SETTINGS_MODULE': 'config.settings.base',
        'IT_APP_ENVIRONMENT': env.str('IT_APP_ENVIRONMENT'),

        'POSTGRES_HOST': f'srv-captain--{app_name}-postgres-db',
        'POSTGRES_PORT': 5432,
        'POSTGRES_DB': db_name,
        'POSTGRES_USER': db_user,
        'POSTGRES_PASSWORD': db_pass,

        'IT_ALLOW_LOCAL_LOGIN': env.str('IT_ALLOW_LOCAL_LOGIN'),

        'IT_DJANGO_SECRET_KEY': env.str('IT_DJANGO_SECRET_KEY'),
        'IT_DJANGO_ADMIN_URL': env.str('IT_DJANGO_ADMIN_URL'),
        'IT_DJANGO_ALLOWED_HOSTS': env.str('IT_DJANGO_ALLOWED_HOSTS'),

        'IT_DJANGO_DEBUG': 'false',
        'IT_SERVE_VUE': 'false',

        'IT_SENTRY_DSN': env.str('IT_SENTRY_DSN'),

        'IT_OAUTH_CLIENT_NAME': env.str('IT_OAUTH_CLIENT_NAME'),
        'IT_OAUTH_CLIENT_ID': env.str('IT_OAUTH_CLIENT_ID'),
        'IT_OAUTH_CLIENT_SECRET': env.str('IT_OAUTH_CLIENT_SECRET'),
        'IT_OAUTH_ACCESS_TOKEN_URL': env.str('IT_OAUTH_ACCESS_TOKEN_URL'),
        'IT_OAUTH_AUTHORIZE_URL': env.str('IT_OAUTH_AUTHORIZE_URL'),
        'IT_OAUTH_API_BASE_URL': env.str('IT_OAUTH_API_BASE_URL'),
        'IT_OAUTH_LOCAL_DIRECT_URI': env.str('IT_OAUTH_LOCAL_DIRECT_URI'),
        'IT_OAUTH_TENANT_ID': env.str('IT_OAUTH_TENANT_ID'),
        'IT_OAUTH_SCOPE': env.str('IT_OAUTH_SCOPE'),
        'IT_OAUTH_SERVER_METADATA_URL': env.str('IT_OAUTH_SERVER_METADATA_URL'),
        'IT_OAUTH_TOKEN_NAME': env.str('IT_OAUTH_TOKEN_NAME'),
        'IT_OAUTH_LOGOUT_URL': env.str('IT_OAUTH_LOGOUT_URL'),
    },
)
