# Скачать кандидатов из results.json по префиксам id. Аргументы: каталог (results.json в нём), префиксы id.
import json, os, sys, urllib.request

d, prefixes = sys.argv[1], sys.argv[2:]
raw = os.path.join(d, "raw")
os.makedirs(raw, exist_ok=True)
results = json.load(open(os.path.join(d, "results.json")))
for p in prefixes:
    r = next(x for x in results if x["id"].startswith(p))
    ext = (r.get("filetype") or os.path.splitext(r["url"])[1].lstrip(".") or "mp3").lower()
    dst = os.path.join(raw, f"{p}.{ext}")
    if not os.path.exists(dst):
        try:
            with urllib.request.urlopen(urllib.request.Request(r["url"], headers={"User-Agent": "pixeloffice-sound-search"}), timeout=180) as res, open(dst, "wb") as fh:
                fh.write(res.read())
        except Exception as e:
            print("ERR", p, e)
            continue
    print(p, os.path.getsize(dst), r["license"], r["license_version"], r["url"])
