"""Integration tests for end-to-end upload and worker pipeline behavior."""

from pathlib import Path

import pytest
from sqlmodel import select

from transcription.config import Settings
from transcription.models import Job, JobStatus, Transcript
from transcription.providers.base import TranscriptionResult
from transcription.services.upload import create_upload_job
from transcription.worker import process_next_queued_job


@pytest.mark.integration
class TestPipelineSuccessFlow:
    """Verify end-to-end success lifecycle behavior."""

    def test_upload_then_worker_persists_transcribed_terminal_state(self, session, tmp_path: Path, monkeypatch):
        """Upload followed by worker processing persists transcript and transcribed status."""
        settings = Settings(openrouter_api_key="test-key", upload_dir=tmp_path)
        upload_result = create_upload_job(
            filename="pipeline.jpg",
            file_bytes=b"pipeline-bytes",
            session=session,
            settings=settings,
        )

        def _fake_transcribe(_path: str) -> TranscriptionResult:
            return TranscriptionResult(text="Pipeline transcript", provider="openrouter", model="test-model")

        monkeypatch.setattr("transcription.worker.transcribe_document_image", _fake_transcribe)

        processed = process_next_queued_job(session=session)
        job = session.get(Job, upload_result.job_id)
        transcript = session.exec(select(Transcript).where(Transcript.job_id == upload_result.job_id)).first()

        assert processed is True
        assert job is not None
        assert job.status == JobStatus.TRANSCRIBED
        assert transcript is not None
        assert transcript.text == "Pipeline transcript"
        assert transcript.error_detail is None


@pytest.mark.integration
class TestPipelineFailureFlow:
    """Verify end-to-end failure lifecycle behavior."""

    def test_upload_then_worker_persists_failed_terminal_state(self, session, tmp_path: Path, monkeypatch):
        """Upload followed by worker processing persists error detail and failed status."""
        settings = Settings(openrouter_api_key="test-key", upload_dir=tmp_path)
        upload_result = create_upload_job(
            filename="pipeline.jpg",
            file_bytes=b"pipeline-bytes",
            session=session,
            settings=settings,
        )

        def _fake_transcribe(_path: str) -> TranscriptionResult:
            raise RuntimeError("pipeline provider failure")

        monkeypatch.setattr("transcription.worker.transcribe_document_image", _fake_transcribe)

        processed = process_next_queued_job(session=session)
        job = session.get(Job, upload_result.job_id)
        transcript = session.exec(select(Transcript).where(Transcript.job_id == upload_result.job_id)).first()

        assert processed is True
        assert job is not None
        assert job.status == JobStatus.FAILED
        assert transcript is not None
        assert transcript.text is None
        assert "pipeline provider failure" in transcript.error_detail
        assert "[internal_unexpected_error]" in transcript.error_detail
        assert "error_id=" in transcript.error_detail
