# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_downloader.ipynb.

# %% auto 0
__all__ = ['hello_world', 'download_summary', 'download_genomes_from_summary', 'download_genomes_from_taxon', 'cli']

# %% ../nbs/01_downloader.ipynb 6
# That export there, it makes sure this code goes into the module.

# standard libs
import os
import re

# Common to template
# add into settings.ini, requirements, package name is python-dotenv, for conda build ensure `conda config --add channels conda-forge`
import dotenv  # for loading config from .env files, https://pypi.org/project/python-dotenv/
import envyaml  # Allows to loads env vars into a yaml file, https://github.com/thesimj/envyaml
import fastcore  # To add functionality related to nbdev development, https://github.com/fastai/fastcore/
from fastcore import (
    test,
)
from fastcore.script import (
    call_parse,
)  # for @call_parse, https://fastcore.fast.ai/script
import json  # for nicely printing json and yaml

# Project specific libraries

import shutil

# %% ../nbs/01_downloader.ipynb 8
from ncbi_datasets_util import (
    core,
)

# %% ../nbs/01_downloader.ipynb 17
def hello_world(name1: str, name2: str) -> str:
    return f"Hello {name1} and {name2}!"

# %% ../nbs/01_downloader.ipynb 19
### Functions


def download_summary(taxon, summary_tsv=None):
    if summary_tsv is None:
        summary_tsv = f"{taxon}_summary.tsv"
    cmd = f"datasets summary genome taxon {taxon} --as-json-lines | dataformat tsv genome > {summary_tsv}"
    print(cmd)
    print(f"Downloading summary tsv for taxon {taxon} to {summary_tsv}")
    os.system(cmd)
    return summary_tsv


def download_genomes_from_summary(
    summary_tsv, output_folder, data_types="genome,rna,cds,protein,gff3,gbff,seq-report"
):
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    accesion_txt = os.path.join(output_folder, "accesions.txt")
    output_zip = os.path.join(output_folder, "ncbi_dataset.zip")
    # unzip_dir = os.path.join(output_folder,"ncbi_dataset")
    cmd = (
        f"sed 's/\t/ /' {summary_tsv} | awk '{{print $1}}' | sed '1d' > {accesion_txt}"
    )
    os.system(cmd)
    cmd = f"datasets download genome accession --inputfile {accesion_txt} --include {data_types} --assembly-version latest --filename {output_zip} --no-progressbar"
    print(
        f"Downloading latest versions of genome data ({data_types}) for entries in {summary_tsv}"
    )
    os.system(cmd)
    cmd = f"unzip -qq {output_zip} -d {output_folder}"
    print(f"Unzipping data to {output_folder}")
    os.system(cmd)
    return output_folder


def download_genomes_from_taxon(taxon, output_folder):
    if os.path.exists(output_folder):
        shutil.rmtree(output_folder)
    os.makedirs(output_folder)
    summary_tsv = os.path.join(output_folder, "ncbi_summary.tsv")
    download_summary(taxon, summary_tsv)
    download_genomes_from_summary(summary_tsv, output_folder)
    return output_folder

# %% ../nbs/01_downloader.ipynb 21
from fastcore.script import call_parse


@call_parse
def cli(
    taxon: str = None,  # Taxonomy name
    output_folder: str = None,  # An alternative name
    config=None,
) -> None:
    """
    This will print Hello World! with your name
    """
    # config = core.get_config(config_file)  # Set env vars and get config variables
    # if output_folder is not None:
    #    config["example"]["input"]["output_folder"] = alternative_name

    download_genomes_from_taxon(taxon, output_folder)
