"""Unit tests for application startup wiring."""


async def test_startup_initializes_registries_before_embed_check(monkeypatch):
    import navi.api.deps as deps
    import navi.api.routes.health as health_mod
    import navi.content_store as content_store
    import navi.main as main_mod
    import navi.session_files as session_files

    order = []

    async def fake_ensure_tables():
        order.append("ensure_tables")

    def fake_get_registries():
        order.append("get_registries")
        return None

    def fake_get_tool_registry():
        order.append("get_tool_registry")
        return None

    async def fake_get_mcp_manager():
        order.append("get_mcp_manager")
        return None

    async def fake_register_mcp_tools(registry, manager):
        order.append("register_mcp_tools")

    async def fake_check_embed():
        order.append("check_embed")
        return {"ok": True, "backend": "fake", "error": None}

    async def fake_cleanup_loop(store):
        return None

    def fake_create_task(coro):
        order.append("create_task")
        coro.close()
        return object()

    monkeypatch.setattr(content_store, "ensure_tables", fake_ensure_tables)
    monkeypatch.setattr(deps, "get_registries", fake_get_registries)
    monkeypatch.setattr(deps, "get_tool_registry", fake_get_tool_registry)
    monkeypatch.setattr(deps, "get_mcp_manager", fake_get_mcp_manager)
    monkeypatch.setattr(deps, "register_mcp_tools", fake_register_mcp_tools)
    monkeypatch.setattr(health_mod, "_check_embed", fake_check_embed)
    monkeypatch.setattr(session_files, "cleanup_loop", fake_cleanup_loop)
    monkeypatch.setattr(deps, "get_session_store", lambda: object())
    monkeypatch.setattr(main_mod.asyncio, "create_task", fake_create_task)
    # Auth tables creation should not break startup test
    import navi.auth as auth_mod
    async def fake_ensure_auth_tables():
        pass
    monkeypatch.setattr(auth_mod, "_ensure_auth_tables", fake_ensure_auth_tables)

    await main_mod._on_startup()

    assert order[:2] == ["ensure_tables", "get_registries"]
    assert "get_mcp_manager" in order
    assert "register_mcp_tools" in order
    assert "check_embed" in order
    assert order[-1] == "create_task"
