from urllib.request import Request, urlopen
from urllib.parse import urlencode
import json
import os

token = os.getenv("ADS_DEV_KEY", "")
print(token)
def get_metrics():
    url = "https://api.adsabs.harvard.edu/v1/metrics"
#    url = "https://ui.adsabs.harvard.edu/
    bibcodes = []
    with open("bibcodes.txt", "r") as f:
        for line in f.readlines():
            bibcodes.append(line.replace("\n", ""))
    bibcodes = '"' + '", "'.join(bibcodes) + '"'
    data = '{"bibcodes": [%s], "types":["timeseries"]}' % bibcodes
    req = Request(url, data.encode("ascii"))
    req.add_header("Authorization", "Bearer %s" % token)
    req.add_header("Content-Type", "application/json")
    content = urlopen(req).read()
    metrics = json.loads(content)
    with open("metrics.json", "w") as json_file:
        json.dump(metrics, json_file)


if __name__ == "__main__":
    get_metrics()
