from __future__ import annotations

from pathlib import Path

from fastapi.testclient import TestClient

from argus.service.app import create_app


def _write_config(tmp_path: Path) -> Path:
    p = tmp_path / "cfg.yaml"
    p.write_text(
        """
ray:
  address: "http://127.0.0.1:8265"
  shared_root: "/private"
  entrypoint_num_cpus: 1
  entrypoint_resources: { worker_node: 1 }
  runtime_env: { env_vars: { PYTHONUNBUFFERED: "1" } }
service:
  api: { host: "127.0.0.1", port: 8080 }
  auth: { token_env: "MVP_INTERNAL_TOKEN" }
  sqlite: { db_path: "%(db)s" }
data:
  user_root: "%(users)s"
  sftpgo: { enabled: false }
  retention: { jobs_trash_after_days: 3, jobs_purge_after_days: 7, janitor_interval_s: 3600 }
serving: {}
"""
        % {"db": str(tmp_path / "mvp.sqlite3"), "users": str(tmp_path / "users")}
    )
    return p


def test_ui_serving_pages_render(tmp_path, monkeypatch):
    cfg = _write_config(tmp_path)
    monkeypatch.setenv("MVP_INTERNAL_TOKEN", "admin-token")
    app = create_app(str(cfg))
    c = TestClient(app)

    for path in ("/ui/serving", "/ui/serving/new", "/ui/serving/any-model-key"):
        r = c.get(path)
        assert r.status_code == 200
        assert "<html" in r.text.lower()


def test_ui_serving_contains_openai_port_8000(tmp_path, monkeypatch):
    cfg = _write_config(tmp_path)
    monkeypatch.setenv("MVP_INTERNAL_TOKEN", "admin-token")
    app = create_app(str(cfg))
    c = TestClient(app)

    r = c.get("/ui/serving")
    assert r.status_code == 200
    assert "curOriginWithPort(8000)" in r.text
    assert "/serve/<model_key>/v1" in r.text
