from datetime import date
from types import SimpleNamespace
from uuid import UUID

from dsg_core.api.v1.routes import comparisons
from dsg_core.services.comparisons.diff import DiffService, DiffSourceSchema
from dsg_core.services.reports.reportService import ReportService


def _build_payload() -> DiffSourceSchema:
    return DiffSourceSchema(
        item_type_id=UUID("4b7acb60-ef3d-4374-9d91-79c3843a7a7a"),
        version="default",
        start_timestamp=date(2026, 4, 1),
        end_timestamp=date(2026, 4, 28),
    )


def test_start_diff_report_generation_reuses_cached_report(monkeypatch) -> None:
    payload = _build_payload()
    request_id = str(
        ReportService.build_report_request_id(DiffService.build_report_payload(payload))
    )

    monkeypatch.setattr(
        comparisons.ReportService,
        "get_cached_report",
        classmethod(
            lambda cls, query_id, *, session: SimpleNamespace(query_id=query_id)
        ),
    )
    monkeypatch.setattr(comparisons, "is_task_already_scheduled", lambda task_id: False)

    response = comparisons.start_diff_report_generation(payload, session=object())

    assert response.job_id == request_id


def test_start_diff_report_generation_schedules_stable_request_id(monkeypatch) -> None:
    payload = _build_payload()
    expected_request_id = str(
        ReportService.build_report_request_id(DiffService.build_report_payload(payload))
    )
    captured: dict[str, object] = {}

    monkeypatch.setattr(
        comparisons.ReportService,
        "get_cached_report",
        classmethod(lambda cls, query_id, *, session: None),
    )
    monkeypatch.setattr(comparisons, "is_task_already_scheduled", lambda task_id: False)

    def _apply_async(*, kwargs, task_id):
        captured["kwargs"] = kwargs
        captured["task_id"] = task_id
        return SimpleNamespace(id=task_id)

    monkeypatch.setattr(comparisons.generate_diff_report, "apply_async", _apply_async)

    response = comparisons.start_diff_report_generation(payload, session=object())

    assert response.job_id == expected_request_id
    assert captured["task_id"] == expected_request_id
    assert captured["kwargs"] == {"payload": payload, "file_name": ""}
