# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/CLI_Helper.ipynb (unless otherwise specified).

__all__ = [
    "logger",
    "requires_auth_token",
    "humanize_date",
    "humanize_number",
    "humanize_size",
]

# Cell

import logging
from typing import *

# Internal Cell

import os
from contextlib import contextmanager
import functools

import typer
import humanize
import datetime as dt
import pandas as pd

from ..client import Client
from ..logger import get_logger, set_level

# Cell

logger = get_logger(__name__)

# Internal Cell


@contextmanager
def authenicate_user():
    Client(
        auth_token=os.environ["AIRT_SERVICE_TOKEN"],
        server=os.environ.get("AIRT_SERVER_URL", None),
    )

    yield


# Cell


def requires_auth_token(func):
    @functools.wraps(func)
    def wrapper_decorator(*args, **kwargs):
        try:

            if ("debug" in kwargs) and kwargs["debug"]:
                set_level(logging.DEBUG)
            else:
                set_level(logging.WARNING)

            with authenicate_user():
                # Do something before
                value = func(*args, **kwargs)
                # Do something after

        except KeyError as e:
            typer.echo(
                message=f"KeyError: The environment variable {e} is not set.", err=True
            )

            if "'AIRT_SERVICE_TOKEN'" in str(e):
                typer.echo(
                    f"\nPlease run the command 'airt token' to get the application token and set it in the "
                    f"environment variable `AIRT_SERVICE_TOKEN`."
                )
                typer.echo(f"\nTry 'airt token --help' for help.")

            raise typer.Exit(code=1)

        except Exception as e:
            typer.echo(message=f"Error: {e}", err=True)
            raise typer.Exit(code=1)
        return value

    return wrapper_decorator


# Cell


def humanize_date(s: pd.Series) -> pd.Series:
    return s.apply(
        lambda date: humanize.naturaltime(
            dt.datetime.now() - dt.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S")
        )
    )


# Cell


def humanize_number(s: pd.Series) -> pd.Series:
    return s.apply(
        lambda num: humanize.intcomma(int(num)) if pd.notna(num) else "unknown"
    )


# Cell


def humanize_size(s: pd.Series) -> pd.Series:
    return s.apply(
        lambda size: humanize.naturalsize(size) if pd.notna(size) else "unknown"
    )
