import os
import subprocess
import tempfile

import joblib


def download_single_file(
    url: str,
    output_dir: str,
    output_file: str,
    max_parallel_connections: int = 16,
    disk_cache_mb: int = 1024,
) -> str:
    max_parallel_connections = joblib.effective_n_jobs(max_parallel_connections)
    cmd = [
        "aria2c",
        url,
        f"--dir={output_dir}",
        f"--out={output_file}",
        f"--split={max_parallel_connections}",
        f"--max-concurrent-downloads={max_parallel_connections}",
        "--max-connection-per-server=16",  # https://github.com/aria2/aria2/issues/1039
        "--optimize-concurrent-downloads=true",
        f"--disk-cache={disk_cache_mb}M",
        "--enable-mmap=true",
        "--continue=true",
    ]
    subprocess.run(cmd, check=True)

    output_path = os.path.join(output_dir, output_file)
    return output_path


def download_multiple_files(
    urls: list[str],
    output_dir: str,
    max_parallel_connections: int = 16,
    disk_cache_mb: int = 1024,
) -> str:
    with tempfile.NamedTemporaryFile(mode="w+", delete=False) as input_file:
        for url in urls:
            input_file.write(url + "\n")
        input_file.close()

        max_parallel_connections = joblib.effective_n_jobs(max_parallel_connections)
        cmd = [
            "aria2c",
            f"--input-file={input_file.name}",
            f"--dir={output_dir}",
            f"--split={max_parallel_connections}",
            f"--max-concurrent-downloads={max_parallel_connections}",
            "--max-connection-per-server=16",  # https://github.com/aria2/aria2/issues/1039
            "--optimize-concurrent-downloads=true",
            f"--disk-cache={disk_cache_mb}M",
            "--enable-mmap=true",
            "--conditional-get=true",
            "--continue=true",
        ]
        subprocess.run(cmd, check=True)

    return output_dir


def unpack_archive(file_path: str) -> None:
    extension = file_path.split(".")[-1]

    if extension == "gz":
        cmd = ["rapidgzip", "-d", file_path, "--force"]
    elif extension == "zip":
        directory = os.path.dirname(file_path)
        cmd = ["unzip", "-d", directory, file_path]
    else:
        raise ValueError(f"Archive extension {extension} not supported")

    subprocess.run(cmd, check=True)
