#!/usr/bin/env python3
import requests
import re
from pathlib import Path
from fire import Fire

DOI_PATTERN = re.compile(r"10\.\d{4,9}/[-._;()/:A-Z0-9]+", re.IGNORECASE)
DEFAULT_COOKIE = "ddhgguuy_session=9mcfl93kd8mnitom6c00mped55"


def download(
    doi,
    base="https://dl-acm-org-s.a8.sjuku.top/doi/pdf",
    cookie=DEFAULT_COOKIE,
):
    headers = {"Cookie": cookie}
    resp = requests.get(f"{base}/{doi}", headers=headers)
    pdf = Path(doi + ".pdf")
    pdf.parent.mkdir(parents=True, exist_ok=True)
    size = pdf.write_bytes(resp.content)
    print(f"Downloaded {pdf} ({size / 1024:.0f} KiB)")


def download_bibtex(
    bib,
):
    text = Path(bib).read_text()
    dois = set(DOI_PATTERN.findall(text))
    print(f"Found {len(dois)} DOIs in {bib}")
    for doi in dois:
        try:
            print(f"Downloading {doi}")
            download(doi)
        except Exception as e:
            print(f"Failed to download {doi}: {e}")


if __name__ == "__main__":
    Fire(download_bibtex)

