# pyright: reportPrivateUsage=false

from __future__ import annotations

import os
from unittest import IsolatedAsyncioTestCase
from unittest.mock import patch

import httpx

_ = os.environ.setdefault("NEON_DATABASE_URL", "postgresql://user:pass@localhost:5432/testdb")
_ = os.environ.setdefault("BETTER_AUTH_URL", "http://localhost:3000")
_ = os.environ.setdefault("INTERNAL_EMAIL_SHARED_SECRET", "test-secret")
_ = os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")

from app import main  # noqa: E402


def _failing_discover_transport(request: httpx.Request) -> httpx.Response:
    return httpx.Response(status_code=503, request=request)


def _static_discover_transport_factory(payload: dict[str, object]):
    def _handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(status_code=200, request=request, json=payload)

    return _handler


class TestStartupDependencyDiagnostics(IsolatedAsyncioTestCase):
    async def test_discover_unavailable_warning_includes_actionable_context(self) -> None:
        warning_calls: list[dict[str, object]] = []

        def fake_warning(message: str, **kwargs: object) -> None:
            warning_calls.append({"message": message, **kwargs})

        async with httpx.AsyncClient(
            transport=httpx.MockTransport(_failing_discover_transport)
        ) as client:
            with patch("app.main.logfire.warning", side_effect=fake_warning):
                await main._emit_startup_dependency_diagnostics(client)

        self.assertEqual(len(warning_calls), 1)
        self.assertEqual(warning_calls[0]["message"], "critical_dependency_diagnostics_failed")
        self.assertEqual(warning_calls[0]["phase"], "startup")
        self.assertEqual(warning_calls[0]["context"], "post_cron_registration")
        self.assertEqual(warning_calls[0]["dependency"], "restate_discover")
        self.assertEqual(
            warning_calls[0]["affected_service_group"],
            "critical_readiness_services",
        )

    async def test_missing_services_warning_includes_actionable_context(self) -> None:
        warning_calls: list[dict[str, object]] = []

        def fake_warning(message: str, **kwargs: object) -> None:
            warning_calls.append({"message": message, **kwargs})

        discover_payload: dict[str, object] = {}
        discover_payload["services"] = [
            {"name": "ReservationWorkflow"},
            {"name": "PaymentService"},
        ]

        async with httpx.AsyncClient(
            transport=httpx.MockTransport(_static_discover_transport_factory(discover_payload))
        ) as client:
            with patch("app.main.logfire.warning", side_effect=fake_warning):
                await main._emit_startup_dependency_diagnostics(client)

        self.assertEqual(len(warning_calls), 1)
        self.assertEqual(warning_calls[0]["message"], "critical_startup_dependencies_missing")
        self.assertEqual(warning_calls[0]["phase"], "startup")
        self.assertEqual(warning_calls[0]["context"], "post_cron_registration")
        self.assertEqual(warning_calls[0]["dependency"], "restate_discover")
        self.assertEqual(
            warning_calls[0]["affected_service_group"],
            "critical_readiness_services",
        )
        self.assertEqual(
            warning_calls[0]["missing_services"],
            ["CleanupService", "CronService", "ReminderService"],
        )
