from typing import IO, List

import click
import requests

from treebeard.conf import secrets_endpoint
from treebeard.helper import get_treebeard_env, validate_notebook_directory

from treebeard.secrets.helper import get_secrets_archive

treebeard_env = get_treebeard_env()


@click.group()
def secrets():
    pass


@secrets.command()
@click.argument("files", type=click.File("r"), nargs=-1)
def push(files: List[IO]):
    """Uploads json document of secrets to Treebeard's servers. These will be available in your notebook directory at runtime"""
    click.echo(f"🌲 Pushing Secrets for project {treebeard_env['project_id']}")
    validate_notebook_directory()
    secrets_archive = get_secrets_archive(files)
    response = requests.post(
        secrets_endpoint,
        files={"secrets": open(secrets_archive.name, "rb")},
        headers=treebeard_env,
    )
    if response.status_code != 200:
        click.echo(
            f"Error: service failure pushing secrets, {response.status_code}: {response.text}"
        )
        return

    click.echo("🔐  done!")
