# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs-dev/0_01_ipython.ipynb.

# %% ../nbs-dev/0_01_ipython.ipynb 2
from __future__ import annotations
from functools import wraps
from IPython.core.getipython import get_ipython
from IPython.display import display, Markdown, display_markdown
from pathlib import Path
from typing import Any, Callable, Optional
from .core import validate_path, validate_type

import configparser
import numpy as np
import pandas as pd
import subprocess
import sys

# %% auto 0
__all__ = ['nb_setup', 'colab_install_project_code', 'display_mds', 'display_dfs', 'df_all_cols_and_rows', 'display_full_df',
           'run_cli']

# %% ../nbs-dev/0_01_ipython.ipynb 5
def nb_setup(autoreload:bool = True,   # True to set autoreload in this notebook
             paths:list(Path) = None   # Paths to add to the path environment variable
            ):
    """Use in first cell of notebook to set autoreload, and paths"""
#   Add paths. Default is 'src' if it exists
    if paths is None:
        p = Path('../src').resolve().absolute()
        if p.is_dir():
            paths = [str(p)]
        else:
            paths=[]
    if paths:
        for p in paths:
            sys.path.insert(1, str(p))
        print(f"Added following paths: {','.join(paths)}")

#   Setup auto reload
    if autoreload:
        ipshell = get_ipython()
        ipshell.run_line_magic('load_ext',  'autoreload')
        ipshell.run_line_magic('autoreload', '2')
        print('Set autoreload mode')

# %% ../nbs-dev/0_01_ipython.ipynb 7
def colab_install_project_code(
    package_name:str # project package name, e.g. git+https://github.com/vtecftwy/metagentools.git@main
):
    """When nb is running on colab, pip install the project code package"""
    try:
        from google.colab import drive
        ON_COLAB = True
        print('The notebook is running on colab')
        print('Installing project code')
        cmd = f"pip install -U {package_name}"
        run(cmd)

    except ModuleNotFoundError:
        ON_COLAB = False
        print('The notebook is running locally, will not automatically install project code')

    return ON_COLAB

# %% ../nbs-dev/0_01_ipython.ipynb 11
def display_mds(
    *strings:str|tuple[str] # any number of strings with text in markdown format
):
    """Display one or several strings formatted in markdown format"""
    for string in strings:
        display_markdown(Markdown(data=string))

# %% ../nbs-dev/0_01_ipython.ipynb 15
def display_dfs(*dfs:pd.DataFrame       # any number of Pandas DataFrames
               ):
    """Display one or several `pd.DataFrame` in a single cell output"""
    for df in dfs:
        display(df)

# %% ../nbs-dev/0_01_ipython.ipynb 18
def df_all_cols_and_rows(
    f:Callable,   # function to apply the decorator ti
)-> Callable:     # decorated function
    """decorator function forcing all rows and columns of `DataFrames` to be displayed in the wrapped function"""
    @wraps(f)
    def wrapper(*args, **kwargs):
        max_rows = pd.options.display.max_rows
        max_cols = pd.options.display.max_columns
        pd.options.display.max_rows = None
        pd.options.display.max_columns = None
        f(*args, **kwargs)
        pd.options.display.max_rows = max_rows
        pd.options.display.max_columns = max_cols
    
    return wrapper

# %% ../nbs-dev/0_01_ipython.ipynb 22
@df_all_cols_and_rows
def display_full_df(
    df:pd.DataFrame  # DataFrame to display
):
    """Display a `DataFrame` showing all rows and columns"""
#     if not isinstance(df, pd.DataFrame): raise TypeError('df must me a pandas DataFrame')
    validate_type(df, pd.DataFrame, raise_error=True)
    display(df)

# %% ../nbs-dev/0_01_ipython.ipynb 28
def run_cli(cmd:str = 'ls -l'   # command to execute in the cli
           ):
    """Runs a cli command from jupyter notebook and print the shell output message
    
    Uses subprocess.run with passed command to run the cli command"""
    p = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
    print(str(p.stdout, 'utf-8'))
