import json
from pathlib import Path

from wsi_embed_client import embed


class _DummyResponse:
    def __init__(self, payload: dict):
        self._payload = payload

    def raise_for_status(self) -> None:
        return None

    def json(self) -> dict:
        return self._payload


def test_embed_saves_file(tmp_path, monkeypatch):
    slide = tmp_path / "case_001.svs"
    slide.write_bytes(b"dummy-slide")

    def fake_post(url, headers, data, files, timeout):  # noqa: ANN001
        assert url.endswith("/v1/embed")
        assert headers["X-API-Key"] == "test-key"
        assert data["model"] == "dummy-model"
        assert files["file"][2] == "application/zip"
        assert timeout == 300
        return _DummyResponse(
            {
                "request_id": "r1",
                "model": "dummy-model",
                "slide_name": "case_001.svs",
                "embedding": [0.1, 0.2, 0.3],
            }
        )

    monkeypatch.setattr("wsi_embed_client.client.requests.post", fake_post)
    result = embed(str(slide), "dummy-model", "test-key", server_url="http://localhost:8000")

    save_path = Path(result["saved_path"])
    assert save_path.exists()
    content = json.loads(save_path.read_text(encoding="utf-8"))
    assert content["slide_name"] == "case_001.svs"
    assert content["embedding"] == [0.1, 0.2, 0.3]
