#!/bin/env python

import json

import requests

cookie = input("Cookie String: ")
key = input("Order Key: ")

response = requests.get(
    f"https://www.humblebundle.com/api/v1/order/{key}", headers={"Cookie": cookie}
)

books = json.loads(response.text)

with open("files.txt", "w") as file:
    for book in books["subproducts"]:
        name = book["human_name"]
        publisher = book["payee"]["human_name"]
        if len(book["downloads"][0]["download_struct"]) > 1:
            for download in book["downloads"][0]["download_struct"]:
                link = download["url"]["web"]
                fileName = f"{name} - {publisher}.{download['name'].lower()}"
                file.write(f"{link}\n")
                file.write(f"   out={fileName.replace('/', ' ')}\n")
        else:
            download = book["downloads"][0]["download_struct"][0]
            link = download["url"]["web"]
            fileName = f"{name} - {publisher}.{download['name'].lower()}"
            file.write(f"{link}\n")
            file.write(f"   out={fileName.replace('/', ' ')}\n")