from pathlib import Path

import requests

from .foundation import DEFAULT_SOURCE_URL, SOURCE_ASSET

REQUEST_TIMEOUT = (10, 120)


def download_source(url=DEFAULT_SOURCE_URL, output_path=SOURCE_ASSET):
    output_path.parent.mkdir(parents=True, exist_ok=True)
    if output_path.exists() and output_path.stat().st_size > 1024:
        print("skip", output_path)
        return output_path

    print("downloading", url)
    with requests.get(url, stream=True, timeout=REQUEST_TIMEOUT) as response:
        response.raise_for_status()
        temp_path = Path(f"{output_path}.part")
        with temp_path.open("wb") as file_handle:
            for chunk in response.iter_content(1024 * 1024):
                if chunk:
                    file_handle.write(chunk)
        temp_path.replace(output_path)

    print("saved", output_path)
    return output_path


def main():
    download_source()


if __name__ == "__main__":
    main()
