import os
from pathlib import Path

import requests


def download_relai_resource(name: str) -> Path:
    """Download a resource from the RELAI repository.
    This method downloads the resource (if necessary) to a cache directory which can be set using
    the environment variable `RELAI_CACHE`. If unspecified, the cache directory defaults to `~/.cache/relai`.

    Args:
        name (str): Name of the resource to download.

    Returns:
        Path: Path to the downloaded resource.
    """
    cache = os.getenv("RELAI_CACHE", "~/.cache/relai")
    cache = Path(cache).expanduser()

    save_path = cache / name
    save_path.parent.mkdir(parents=True, exist_ok=True)

    if not save_path.exists():
        url = f"https://relai-resources.s3.amazonaws.com/{name}"

        response = requests.get(url)

        if response.ok:
            save_path.write_bytes(response.content)
        else:
            print(f"Failed to download the resource: {name}")
            response.raise_for_status()

    return save_path
