# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/06_export.ipynb.

# %% auto 0
__all__ = ['banner_images', 'default_line_filter', 'filter_out_lines', 'export_cell', 'colab_github_url', 'colab_url',
           'remove_banner_image', 'export_nbs']

# %% ../nbs/06_export.ipynb 3
import os
from pathlib import Path
from rich.markdown import Markdown
from fastcore.script import call_parse, Param, store_true

from .colab import has_colab_badge, get_colab_url
from .utils import find_nbs, read_nb, is_nb, github_url

# %% ../nbs/06_export.ipynb 8
def _export_code_cell(source):
    "Wrap code around python"
    return f"\n```python\n{source}\n```\n\n"

def default_line_filter(line):
    "Remove colab link and @wandbcode"
    if "colab.research" in line:
        return False
    elif "@wandbcode" in line:
        return False
    else: 
        return True

def filter_out_lines(source, f=default_line_filter):
    "Filter lines from source with filter f"
    lines = source.split("\n")
    return "\n".join(filter(f, lines))

def _export_md_cell(source):
    source = filter_out_lines(source)
    if source.strip() == "":
        return None
    return f"{source}\n"

# %% ../nbs/06_export.ipynb 10
def export_cell(cell, debug=False):
    "Export cell source to string"
    source = cell["source"]
    if debug:
        print(source)
    if cell["cell_type"] == "markdown":
        return _export_md_cell(source)
        
    elif cell["cell_type"] == "code":
        return  _export_code_cell(source)
    else:
        return ""

# %% ../nbs/06_export.ipynb 13
def colab_github_url(file):
    "Create a fresh colab URL from file, must be on github repo"
    gh_url = github_url(file)
    colab_url = get_colab_url(file, branch="master")

    return (
        f'\n\n[![Run in Google Colab](https://www.tensorflow.org/images/colab_logo_32px.png)]({colab_url}) [Run in Google Colab]({colab_url})'
        ' &nbsp; '
        f'[![View source on GitHub](https://www.tensorflow.org/images/GitHub-Mark-32px.png)]({gh_url}) [View source on GitHub]({gh_url})'
        '\n\n'
    )

# %% ../nbs/06_export.ipynb 16
def colab_url(file):
    "Create a fresh colab URL from file, must be on github repo"
    url = get_colab_url(file, branch="master")
#     return f'\n[![](https://colab.research.google.com/assets/colab-badge.svg)]({url})\n\n'
    return f"\n[**Try in a Colab Notebook here →**]({url})\n\n"

# %% ../nbs/06_export.ipynb 19
banner_images = ["mini-diagram", "logo-im-png", "uEtWSEb.png", "gb6B4ig.png"]

def remove_banner_image(cells, max_idx=4):
    "Remove banner from top of the notebook"
    exported_cells = []
    for i, cell in enumerate(cells):
        if any([b in cell for b in banner_images]) and i<=max_idx:
            pass
        else:
            exported_cells.append(cell)
    return exported_cells

# %% ../nbs/06_export.ipynb 26
def _export_one(path, outfile, verbose=False):
    
    notebook = read_nb(path)
    
    cells = notebook["cells"]
    
    exported_cells = []
    for cell in cells:
        md_cell = export_cell(cell)
        source = cell["source"]
        if verbose:
            print(f"=================\nInput: \n {source}")
            print(f"-----------------\nMD: \n {md_cell}")
        exported_cells.append(md_cell)
    
    # remove void cells
    exported_cells = [c for c in exported_cells if c is not None]
    
    # remove banner image
    exported_cells = remove_banner_image(exported_cells)
    
    # add colab link
    colab_link_md = colab_github_url(path)
    exported_cells.insert(1, colab_link_md)
    
    with open(outfile, "w") as f:
        f.writelines(exported_cells)

# %% ../nbs/06_export.ipynb 27
@call_parse
def export_nbs(
    path: Param("A path to nb files, can be a list.txt", Path, nargs="?", opt=False) = os.getcwd(),
    verbose: Param("Print errors along the way", store_true) = False,
    outpath: Param("An output folder to save the exported notebooks", Path) = Path(".") ,
):
    path = Path(path)
    files = find_nbs(path)
    outpath = Path(outpath)
    
    for nb_path in files:
        if not is_nb(nb_path):
            raise Exception(f"This {nb_path} is not a notebook!")
        outfile = outpath/(nb_path.with_suffix(".md").name)
        print(f"Exporting notebook {nb_path} -> {outfile}")
        _export_one(nb_path, outfile, verbose=verbose)
