import requests
from time import sleep


def download(name, index):
    url = f"https://api.xingzhige.com/API/Kugou_GN_new/?name={name}&n={index+1}"
    resp = requests.get(url)
    resp.close()
    music_name = resp.json()["data"]["songname"]
    singer = resp.json()["data"]["name"]
    music_url = resp.json()["data"]["src"]
    response = requests.get(music_url, stream=True)
    formated = music_url.split("?")[0].rsplit(".", 1)[1]
    filename_without_endswith = f"{singer} - {music_name}"
    filename = f"{filename_without_endswith}.{formated}"
    filename = filename.replace("\\", "#").replace("/", "#")
    filename = filename.replace(":", "#").replace("*", "#")
    filename = filename.replace("?", "#").replace("\"", "#")
    filename = filename.replace("<", "#").replace(">", "#").replace("|", "#")
    with open(filename, "wb") as f:
        for data in response.iter_content(chunk_size=1024):
            f.write(data)
    response.close()


def get_data(name):
    url = f"https://api.xingzhige.com/API/Kugou_GN_new/?name={name}"
    resp = requests.get(url)
    resp.close()
    music_list = resp.json()["data"]
    for i in range(len(music_list)):
        print(f"{i+1}.{music_list[i]['songname']} - {music_list[i]['name']}")


while True:
    music = input("请输入要搜索的音乐(歌名-歌手):")
    get_data(music)
    try:
        index = int(input("请输入歌曲的编号(什么都不输默认退出):")) - 1
    except:
        continue
    
    if index >= 10:
        continue

    try:
        download(music, index)
        print("下载完成!")
    except Exception as e:
        print(e)
    sleep(2)