"""CLI entry point for huntpdf."""

import argparse
import json
import sys
from pathlib import Path

from huntpdf.detect import InputType, detect
from huntpdf.errors import HuntPDFError
from huntpdf.resolvers.arxiv import resolve_arxiv
from huntpdf.resolvers.doi import resolve_doi
from huntpdf.resolvers.pmc import resolve_pmc
from huntpdf.resolvers.pubmed import resolve_pubmed
from huntpdf.resolvers.url import resolve_url


def fetch(query: str, output: Path | None = None) -> Path:
    """Detect input type, dispatch to the right resolver, and return the PDF path."""
    detected = detect(query)
    match detected.input_type:
        case InputType.ARXIV_ID:
            return resolve_arxiv(detected.value, output)
        case InputType.DOI:
            return resolve_doi(detected.value, output)
        case InputType.PMC_ID:
            return resolve_pmc(detected.value, output)
        case InputType.PMID:
            return resolve_pubmed(detected.value, output)
        case InputType.URL:
            return resolve_url(detected.value, output)


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(
        prog="huntpdf",
        description="Fetch PDFs of arxiv, DOI, and PubMed articles.",
    )
    parser.add_argument("query", help="URL, DOI, arXiv ID, or PubMed ID")
    parser.add_argument(
        "-o", "--output",
        help="Save PDF to this path (default: auto-generated in current directory)",
    )
    args = parser.parse_args(argv)

    output = Path(args.output) if args.output else None

    try:
        pdf_path = fetch(args.query, output)
        print(json.dumps({"status": "success", "pdf_path": str(pdf_path.resolve())}))
    except HuntPDFError as exc:
        print(json.dumps({"status": "failure", "error": str(exc)}))
        sys.exit(1)


if __name__ == "__main__":
    main()
