"""Tests for the memory-provider serve entrypoint (ratatoskr.provider.serve_memory).

Only the env -> app seam is unit-tested; uvicorn.run is the untestable shell.
"""
from __future__ import annotations

import pytest

from ratatoskr.provider.serve_memory import build_memory_app_from_env


def test_build_memory_app_from_env_requires_heimdall_key():
    with pytest.raises(RuntimeError):
        build_memory_app_from_env(
            {"RATATOSKR_MEMORY_DB": ":memory:", "RATATOSKR_MEMORY_EMBEDDING_DIM": "8"}
        )


def test_build_memory_app_from_env_requires_embedding_dim():
    # A wrong/missing dim silently breaks vector search -> require it explicitly.
    with pytest.raises(RuntimeError):
        build_memory_app_from_env(
            {"RATATOSKR_HEIMDALL_KEY": "k", "RATATOSKR_MEMORY_DB": ":memory:"}
        )


def test_build_memory_app_from_env_rejects_non_positive_dim():
    with pytest.raises(RuntimeError):
        build_memory_app_from_env(
            {
                "RATATOSKR_HEIMDALL_KEY": "k",
                "RATATOSKR_MEMORY_DB": ":memory:",
                "RATATOSKR_MEMORY_EMBEDDING_DIM": "0",
            }
        )


def test_build_memory_app_from_env_builds_app_with_routes():
    app = build_memory_app_from_env(
        {
            "RATATOSKR_HEIMDALL_KEY": "shared-secret",
            "RATATOSKR_MEMORY_DB": ":memory:",
            "RATATOSKR_MEMORY_EMBEDDING_DIM": "8",
        }
    )
    paths = {getattr(r, "path", None) for r in app.routes}
    assert "/bifrost/handshake" in paths
    assert "/bifrost/memory-call" in paths


def test_opfeed_path_wraps_app(tmp_path):
    # Issue #17 slice 2: RATATOSKR_OPFEED_PATH opts the dispatch op-feed in; the
    # returned app is then the instrumented ASGI wrapper, not the raw Starlette.
    app = build_memory_app_from_env(
        {
            "RATATOSKR_HEIMDALL_KEY": "shared-secret",
            "RATATOSKR_MEMORY_DB": ":memory:",
            "RATATOSKR_MEMORY_EMBEDDING_DIM": "8",
            "RATATOSKR_OPFEED_PATH": str(tmp_path / "ops.jsonl"),
        }
    )
    assert not hasattr(app, "routes")  # wrapped: a bare ASGI callable
