#!/usr/bin/env python3
"""Minimal Unpaywall DOI lookup.
Usage:
  python3 unpaywall_lookup.py 10.1257/jep.37.4.155

Outputs JSON with best OA location + URL(s).
"""
import json, os, sys
import urllib.parse
import urllib.request

def main():
    if len(sys.argv) < 2:
        print("need DOI", file=sys.stderr)
        sys.exit(2)
    doi = sys.argv[1].strip()
    email = os.environ.get("USER_EMAIL") or os.environ.get("UNPAYWALL_EMAIL")
    if not email:
        raise SystemExit("Missing USER_EMAIL or UNPAYWALL_EMAIL env var")
    url = f"https://api.unpaywall.org/v2/{urllib.parse.quote(doi)}?email={urllib.parse.quote(email)}"
    with urllib.request.urlopen(url) as r:
        data = json.load(r)
    # reduce
    out = {
        "doi": data.get("doi"),
        "is_oa": data.get("is_oa"),
        "oa_status": data.get("oa_status"),
        "best_oa_location": data.get("best_oa_location"),
        "oa_locations": data.get("oa_locations"),
    }
    print(json.dumps(out, ensure_ascii=False, indent=2))

if __name__ == "__main__":
    main()
