# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.

# %% auto 0
__all__ = ['save_kaggle_creds', 'dl_kaggle']

# %% ../nbs/00_core.ipynb 3
from pathlib import Path  # For working with file paths
import json

# %% ../nbs/00_core.ipynb 4
def save_kaggle_creds(username:str, # The Kaggle API username.
                      key:str, # The Kaggle API key.
                      overwrite=False): # Overwrite existing credentials.
    """
    Save the Kaggle API credentials.
    """
    
    if username == "":
        print("Empty username.")
        return
    if key == "":
        print("Empty key.")
        return
    
    # Set the path to the kaggle.json file
    cred_path = Path('~/.kaggle/kaggle.json').expanduser()

    # Check if the file already exists
    if not cred_path.exists() or overwrite:
        # Create the directory if it does not exist
        cred_path.parent.mkdir(exist_ok=True)
        # Save the API key to the file
        with open(cred_path, "w") as write_file: 
            json.dump({"username": username, "key": key}, write_file)
        # Set the file permissions to be readable and writable by the current user
        cred_path.chmod(0o600)
    else:
        print("Credentials already present. Set `overwrite=True` to replace them.")

# %% ../nbs/00_core.ipynb 6
from cjm_psl_utils.core import file_extract

# %% ../nbs/00_core.ipynb 7
def dl_kaggle(kaggle_dataset, # The Kaggle dataset id in the format `'<username>/<dataset_name>'`.
              archive_path, # The path to save the archive file.
              dataset_path, # The path to save the extracted dataset.
              delete_archive=True): # Delete the archive after extraction.
    """
    Download the Kaggle dataset and extract it to the specified directory. 
    """
    
    # Import the API module from the kaggle package
    from kaggle import api
    
    # If the dataset does not exist in the specified directory, download and extract it.
    if not dataset_path.exists():
        api.dataset_download_cli(kaggle_dataset, path=archive_path.parent)

        file_extract(fname=archive_path, dest=dataset_path.parent)

        # Delete the archive if specified
        if delete_archive: archive_path.unlink()
    else:
        # Inform the user that the dataset already exists in the specified directory.
        print("Dataset already downloaded")
