import re


def compile_url(
    accession_number,
    assembly_name,
    suffix,
    ftpstem="ftp://ftp.ncbi.nlm.nih.gov/genomes/all",
):
    """Compile url for file download.

    Reformate assembly name, replacing escape characters with underscors.
    This is because NCBI records can include a variety of escape characters
    in its records, but requires inclusion of underscores within its urls.

    Use ccession number and assembly name to generate file stem.

    Use the file stem to arquire the GCstem (region of the url which
    dictates the type of genome record, i.e. reference (GCF) or assembly (GCA)),
    and accession number block (in the format of nnn/nnn/nnn in the url).

    Regions of the url are compiled together with the ftpstem (prefix):
    "ftp://ftp.ncni.nlm.nih.gov/genomes/all/".

    :param accession_number: str, asseccion number of genomic assembly
    :param assembly_name: str, name of genomic assembly from NCBI record
    :param logger: logger object

    Return str, url required for download.
    """
    # Extract assembly name, removing alterantive escape characters
    escape_characters = re.compile(r"[\s/,#\(\)]")
    escape_name = re.sub(escape_characters, "_", assembly_name)

    # compile filstem
    filestem = "_".join([accession_number, escape_name])

    # separate out filesteam into GCstem, accession number intergers and discarded
    url_parts = tuple(filestem.split("_", 2))

    # separate identifying numbers from version number
    sub_directories = "/".join(
        [url_parts[1][i : i + 3] for i in range(0, len(url_parts[1].split(".")[0]), 3)]
    )

    # return url for downloading file
    return (
        "{0}/{1}/{2}/{3}/{3}_{4}".format(
            ftpstem, url_parts[0], sub_directories, filestem, suffix
        ),
        filestem,
    )