# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_config.ipynb.

# %% auto 0
__all__ = ['strip_comments', 'handle_config']

# %% ../nbs/03_config.ipynb 1
# from friendlly.utils import nict
from .notebook import detect_environment, update_code_self
import warnings

# %% ../nbs/03_config.ipynb 2
def strip_comments(source: str):
    """Strips Python # comments"""
    lines = source.splitlines()
    return "\n".join([ l.split("#")[0] for l in lines ]).strip()

def handle_config(cell, global_config):

    cell = strip_comments(cell)
    # If the cell was empty, show the config
    if not cell:
        def value_to_str(v):
            if isinstance(v, str):
                if "\n" in v:
                    return f'"""{v}"""'
                else:
                    return f"'{str(v)}'"
            return str(v)

        cell = "\n".join([f"{k}={value_to_str(v)}" for k, v in global_config.items()])
        update_code_self("%%fr config\n" + cell)
    else:
        new_config = {}
        # Code, globals, locals. We want the locals
        exec(cell, {}, new_config)
        global_config.update(new_config)

        if global_config.autorun and global_config.environment != "nbclassic":
            warnings.warn("Autorun is only supported in nbclassic environment at the moment.")

        if global_config.md_cells and global_config.environment != "nbclassic":
            warnings.warn("Inserting Markdown cells is only supported in nbclassic environment at the moment.")
        if global_config.api_key:
            warnings.warn("FIY It's safer to set ANTHROPIC_API_KEY in the environment or even better .env file and use dotenv package to load it.")
