from __future__ import annotations

import sys
from pathlib import Path

import pytest


def test_server_main_calls_uvicorn(monkeypatch, tmp_path: Path):
    import server as server_mod

    cfg = tmp_path / "cfg.yaml"
    cfg.write_text(
        "ray:\n  address: http://127.0.0.1:8265\n  shared_root: /private\n  entrypoint_resources: {worker_node: 1}\n"
        "service:\n  api: {host: 127.0.0.1, port: 18080}\n  sqlite: {db_path: /tmp/x.sqlite3}\n",
        encoding="utf-8",
    )

    got = {}

    monkeypatch.setattr(server_mod, "create_app", lambda path: object())
    monkeypatch.setattr(server_mod.uvicorn, "run", lambda app, host, port, log_level: got.update({"host": host, "port": port}))
    monkeypatch.setattr(sys, "argv", ["server.py", "--config", str(cfg)])

    assert server_mod.main() == 0
    assert got["host"] == "127.0.0.1"
    assert got["port"] == 18080


def test_server_requires_mapping_root(monkeypatch, tmp_path: Path):
    import server as server_mod

    cfg = tmp_path / "bad.yaml"
    cfg.write_text("- 1\n- 2\n", encoding="utf-8")
    monkeypatch.setattr(sys, "argv", ["server.py", "--config", str(cfg)])
    with pytest.raises(SystemExit, match="config yaml must be a mapping"):
        server_mod.main()

