from time import monotonic, sleep

from app.services import pdf_pregeneration


def test_pdf_pregeneration_job_deduplicates_and_tracks_progress(monkeypatch):
    calls: list[tuple[int, int]] = []

    def fake_pre_generate_certificate_pdf(certificate_id: int, concurrency_limit: int) -> str:
        calls.append((certificate_id, concurrency_limit))
        return {101: "generated", 102: "cached", 103: "skipped"}[certificate_id]

    monkeypatch.setattr(pdf_pregeneration, "pre_generate_certificate_pdf", fake_pre_generate_certificate_pdf)

    manager = pdf_pregeneration.PdfPregenerationManager()
    job = manager.start([101, 102, 102, 103], concurrency_limit=2)

    deadline = monotonic() + 2
    while job.status == "running" and monotonic() < deadline:
        sleep(0.01)

    assert job.status == "completed"
    assert job.total == 3
    assert job.completed == 3
    assert job.generated == 1
    assert job.cached == 1
    assert job.skipped == 1
    assert job.failed == 0
    assert sorted(certificate_id for certificate_id, _ in calls) == [101, 102, 103]
    assert {limit for _, limit in calls} == {2}
    assert job.to_dict()["percent"] == 100
