"""Resolve arXiv IDs to PDF files."""

import shutil
import tempfile
from pathlib import Path

import arxiv

from huntpdf.errors import PDFNotFound


def resolve_arxiv(arxiv_id: str, output: Path | None = None) -> Path:
    """Download the PDF for an arXiv paper.

    Args:
        arxiv_id: An arXiv identifier (e.g. "2301.07041" or "hep-ph/9905221").
        output: Optional destination path. Defaults to current directory.

    Returns:
        Path to the downloaded PDF.

    Raises:
        PDFNotFound: If the arXiv ID does not match any paper.
    """
    client = arxiv.Client()
    search = arxiv.Search(id_list=[arxiv_id])
    results = list(client.results(search))

    if not results:
        raise PDFNotFound(f"No arXiv paper found for ID: {arxiv_id}")

    result = results[0]
    safe_id = arxiv_id.replace("/", "_")

    if output is None:
        output = Path.cwd() / f"{safe_id}.pdf"

    with tempfile.TemporaryDirectory() as tmpdir:
        downloaded = Path(result.download_pdf(dirpath=tmpdir))
        output.parent.mkdir(parents=True, exist_ok=True)
        shutil.move(str(downloaded), str(output))

    return output
