"""Tests for huntpdf.resolvers.arxiv."""

from pathlib import Path
from unittest.mock import MagicMock

import pytest

from huntpdf.errors import PDFNotFound
from huntpdf.resolvers.arxiv import resolve_arxiv


class _FakeResult:
    def __init__(self, arxiv_id):
        self.entry_id = f"http://arxiv.org/abs/{arxiv_id}"

    def download_pdf(self, dirpath):
        pdf_path = Path(dirpath) / "fake.pdf"
        pdf_path.write_bytes(b"%PDF-1.4 fake")
        return str(pdf_path)


def _patch_arxiv(monkeypatch, results):
    mock_client = MagicMock()
    mock_client.results.return_value = iter(results)
    monkeypatch.setattr("huntpdf.resolvers.arxiv.arxiv.Client", lambda: mock_client)
    monkeypatch.setattr("huntpdf.resolvers.arxiv.arxiv.Search", MagicMock)
    return mock_client


class TestResolveArxiv:
    def test_successful_download(self, monkeypatch, tmp_path):
        _patch_arxiv(monkeypatch, [_FakeResult("2301.07041")])
        result = resolve_arxiv("2301.07041", tmp_path / "paper.pdf")
        assert result == tmp_path / "paper.pdf"
        assert result.exists()

    def test_paper_not_found(self, monkeypatch):
        _patch_arxiv(monkeypatch, [])
        with pytest.raises(PDFNotFound, match="No arXiv paper found"):
            resolve_arxiv("9999.99999")

    def test_default_output_path(self, monkeypatch, tmp_path, monkeypatch_cwd=None):
        _patch_arxiv(monkeypatch, [_FakeResult("2301.07041")])
        monkeypatch.chdir(tmp_path)
        result = resolve_arxiv("2301.07041")
        assert result == tmp_path / "2301.07041.pdf"
        assert result.exists()

    def test_old_style_id_filename(self, monkeypatch, tmp_path):
        _patch_arxiv(monkeypatch, [_FakeResult("hep-ph/9905221")])
        result = resolve_arxiv("hep-ph/9905221", tmp_path / "paper.pdf")
        assert result == tmp_path / "paper.pdf"
        assert result.exists()

    def test_default_filename_replaces_slashes(self, monkeypatch, tmp_path):
        _patch_arxiv(monkeypatch, [_FakeResult("hep-ph/9905221")])
        monkeypatch.chdir(tmp_path)
        result = resolve_arxiv("hep-ph/9905221")
        assert result.name == "hep-ph_9905221.pdf"
