"""Files reader and writer."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/api/inout.ipynb.

# %% auto 0
__all__ = ['write_toml', 'flatten_dict', 'read_toml']

# %% ../nbs/api/inout.ipynb 2
import tomli_w
import tomli
from typing import Dict, Any

# %% ../nbs/api/inout.ipynb 3
def write_toml(fname: str, cfg: Dict[str, Any]):
    "Write a TOML file from a dictionary."
    none_keys = [k for k, v in flatten_dict(cfg).items() if v is None]
    if none_keys:
        print(f"Warning: The following config keys have None values: {', '.join(none_keys)}")
        
    print(f'Creating {fname}')
    with open(fname, "wb") as f:
        tomli_w.dump(cfg, f)

# %% ../nbs/api/inout.ipynb 4
def flatten_dict(d: Dict[str, Any], parent_key: str = '', sep: str = '.') -> Dict[str, Any]:
    """Flatten a nested dictionary."""
    items = []
    for k, v in d.items():
        new_key = f"{parent_key}{sep}{k}" if parent_key else k
        if isinstance(v, dict):
            items.extend(flatten_dict(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)

# %% ../nbs/api/inout.ipynb 5
def read_toml(fname):
    "Read a TOML file into a dictionary."
    with open(fname, "rb") as f:
        config = tomli.load(f)
    return config
