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

__all__ = ['rename', 'fix_colab_links', 'REGEX', 'fix_nbs_colab_links']

# Cell
from pathlib import Path
from fastcore.script import call_parse
import json
import re
import io


# Cell
@call_parse
def rename(dir: str,  # dir in which to rename files
           suffix: str = ".ipynb"  # suffix of files to change
           ):
    """Rename notebooks to base 1 for chapters."""
    path = Path(dir)
    assert path.exists(), f"dir '{dir}' not found"
    assert path.is_dir(), f"'{dir}' is not a directory"
    print("Renaming notebooks now.")
    for ch in list(range(8, -1, -1)):
        print(f"Renaming chapter {ch}:")
        for x in path.glob(f"S{ch}*{suffix}"):
            new_name = path / x.name.replace(f"S{ch}", f"S{ch+1}")
            print(f"Renaming {x} to {new_name}")
            x.rename(new_name)


# Cell

REGEX = re.compile(
    '<a href="https://colab.research.google.com/github/gtbook/robotics/blob/main/(.+?)\.ipynb".*')


def _colab_link_name(nb):
    colab_link_source = nb['cells'][0]['source'][0]
    result = re.search(REGEX, colab_link_source)
    return result.group(1) if result is not None else None


def fix_colab_links(nb: dict, name: str):
    "Fix colab links in `nb`"

    # Fix colab link
    before = _colab_link_name(nb)
    if before is not None:
        colab_link_source = nb['cells'][0]['source'][0]
        nb['cells'][0]['source'][0] = colab_link_source.replace(before, name)

    # Fix colab metadata
    if 'colab' in nb['metadata']:
        nb['metadata']['colab']['name'] = name + '.ipynb'


# Cell
@call_parse
def fix_nbs_colab_links(dir: str,  # dir in which to rename files
                        ):
    """Fix colab links in all notebooks in directory."""
    path = Path(dir)
    assert path.exists(), f"dir '{dir}' not found"
    assert path.is_dir(), f"'{dir}' is not a directory"
    print("Fixing notebooks now.")
    for x in path.glob("*.ipynb"):
        nb = json.loads(open(str(x), 'r', encoding='utf-8').read())
        fix_colab_links(nb, str(x.stem))
        all = json.dumps(nb, sort_keys=True, indent=1, ensure_ascii=False)
        with io.open(x, 'w', encoding='utf-8') as f:
            f.write(all)
            f.write("\n")
