"""Resolve PubMed IDs to PDF files."""

from pathlib import Path

import httpx

from huntpdf.errors import PDFNotFound
from huntpdf.resolvers.doi import resolve_doi
from huntpdf.resolvers.pmc import resolve_pmc

_IDCONV_URL = "https://www.ncbi.nlm.nih.gov/pmc/utils/idconv/v1.0/"


def resolve_pubmed(pmid: str, output: Path | None = None) -> Path:
    """Download the PDF for a PubMed article.

    Converts the PMID to a PMCID or DOI using the NCBI ID Converter API,
    then delegates to the appropriate resolver.

    Args:
        pmid: A PubMed identifier (e.g. "12345678").
        output: Optional destination path. Defaults to current directory.

    Returns:
        Path to the downloaded PDF.

    Raises:
        PDFNotFound: If no PMCID or DOI can be resolved for the PMID.
    """
    response = httpx.get(
        _IDCONV_URL,
        params={"ids": pmid, "format": "json"},
        timeout=30.0,
    )
    response.raise_for_status()

    data = response.json()
    records = data.get("records", [])

    if not records:
        raise PDFNotFound(f"No records found for PMID: {pmid}")

    record = records[0]
    pmcid = record.get("pmcid")
    doi = record.get("doi")

    if pmcid:
        return resolve_pmc(pmcid, output)

    if doi:
        return resolve_doi(doi, output)

    raise PDFNotFound(
        f"No PMCID or DOI found for PMID: {pmid}. "
        "Cannot locate a downloadable PDF."
    )
