"""Reliability tests for worker workflow timeout behavior."""

from pathlib import Path
from uuid import uuid4

import pytest

from transcription.config import Settings
from transcription.db.models import Document
from transcription.db.models import Job
from transcription.db.models import JobStatus
from transcription.db.models import Source
from transcription.services import ServiceBundle
from transcription.services.workflows import process_queued_job


@pytest.mark.integration
class TestWorkflowReliability:
    """Verify timeout and terminal-state reliability behavior."""

    @pytest.mark.asyncio
    async def test_process_queued_job_timeout_marks_job_failed(self, default_session_factory, monkeypatch):
        """Provider timeout transitions a queued job to failed with error detail."""
        services = ServiceBundle()
        object.__setattr__(
            services,
            "documents",
            services.documents.__class__(session_factory=default_session_factory),
        )
        object.__setattr__(
            services,
            "jobs",
            services.jobs.__class__(session_factory=default_session_factory),
        )
        object.__setattr__(
            services,
            "transcriptions",
            services.transcriptions.__class__(session_factory=default_session_factory),
        )

        async with services.jobs._session_scope() as session:
            document = Document(id=uuid4(), name="timeout-doc")
            session.add(document)
            await session.flush()

            job = Job(document_id=document.id, status=JobStatus.QUEUED)
            session.add(job)
            await session.flush()

            source = Source(
                document_id=document.id,
                job_id=job.id,
                upload_name="timeout.jpg",
                filename="timeout.jpg",
                file_path=str(Path("tests/fixtures/images/real/Book Two - page 02.jpg")),
            )
            session.add(source)
            await session.commit()

            loaded = await services.jobs.read_job(job_id=job.id, session=session)

        async def _never_returns(image_path, *, prompt_name="transcribe_document.md", settings=None, provider=None):
            _ = (image_path, prompt_name, settings, provider)
            raise TimeoutError("simulated provider timeout")

        monkeypatch.setattr("transcription.services.workflows.transcribe_document_image", _never_returns)

        timeout_settings = Settings(openrouter_api_key="test-key", worker_provider_timeout_seconds=20.0)
        result = await process_queued_job(job=loaded, services=services, settings=timeout_settings)

        assert result is not None
        assert result.status == JobStatus.FAILED
        assert result.error_detail is not None
        assert "timed out" in result.error_detail.lower()
        assert "20.0s" in result.error_detail
