"""Tests for transcription.app."""

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from transcription.app import create_app


@pytest.mark.unit
class TestAppFactory:
    """Verify FastAPI app factory wiring."""

    def test_create_app_returns_fastapi_instance(self):
        """create_app returns a FastAPI application instance."""
        app = create_app()
        assert isinstance(app, FastAPI)


@pytest.mark.integration
class TestAppLifespan:
    """Verify startup and shutdown lifecycle behavior."""

    def test_startup_initializes_runtime_dependencies(self, monkeypatch):
        """Startup initializes logging, schema, directories, and worker resources."""
        calls = []

        monkeypatch.setattr("transcription.app.configure_logging", lambda: calls.append("logging"))

        async def _create_all(**_kwargs):
            calls.append("schema")

        monkeypatch.setattr("transcription.app.create_all", _create_all)
        monkeypatch.setattr(
            "transcription.app.initialize_database_runtime",
            lambda **_kwargs: type("_Runtime", (), {"engine": object(), "session_factory": object()})(),
        )

        async def _cleanup_database():
            calls.append("dispose_db")

        monkeypatch.setattr("transcription.app.cleanup_database", _cleanup_database)
        monkeypatch.setattr("transcription.app._start_worker", lambda _app: calls.append("start_worker"))
        monkeypatch.setattr("transcription.app._stop_worker", lambda _app: calls.append("stop_worker"))

        class _Dir:
            def mkdir(self, parents: bool, exist_ok: bool):
                calls.append("mkdir")

        class _Settings:
            should_bootstrap_schema = True
            upload_dir = _Dir()
            prompt_dir = _Dir()

        monkeypatch.setattr("transcription.app.get_settings", lambda: _Settings())

        app = create_app()
        with TestClient(app):
            pass

        assert "logging" in calls
        assert "schema" in calls
        assert "mkdir" in calls
        assert "start_worker" in calls
        assert "dispose_db" in calls

    def test_shutdown_stops_worker_resources(self, monkeypatch):
        """Shutdown signals and stops worker resources cleanly."""
        calls = []

        monkeypatch.setattr("transcription.app.configure_logging", lambda: None)

        async def _create_all(**_kwargs):
            return None

        monkeypatch.setattr("transcription.app.create_all", _create_all)
        monkeypatch.setattr(
            "transcription.app.initialize_database_runtime",
            lambda **_kwargs: type("_Runtime", (), {"engine": object(), "session_factory": object()})(),
        )

        async def _cleanup_database():
            calls.append("dispose_db")

        monkeypatch.setattr("transcription.app.cleanup_database", _cleanup_database)
        monkeypatch.setattr("transcription.app._start_worker", lambda _app: calls.append("start_worker"))
        monkeypatch.setattr("transcription.app._stop_worker", lambda _app: calls.append("stop_worker"))

        class _Dir:
            def mkdir(self, parents: bool, exist_ok: bool):
                return None

        class _Settings:
            should_bootstrap_schema = True
            upload_dir = _Dir()
            prompt_dir = _Dir()

        monkeypatch.setattr("transcription.app.get_settings", lambda: _Settings())

        app = create_app()
        with TestClient(app):
            pass

        assert calls == ["start_worker", "stop_worker", "dispose_db"]
