# retoor <retoor@molodetz.nl>

import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot
from devplacepy.services.jobs import queue


def _json_headers():
    return {"Accept": "application/json"}


def _clear():
    refresh_snapshot()
    jobs = get_table("jobs")
    for row in list(jobs.find(kind="deepsearch")):
        jobs.delete(uid=row["uid"])


def test_status_shape_for_pending_job(app_server):
    try:
        uid = queue.enqueue(
            "deepsearch",
            {"query": "a research question", "depth": 2, "max_pages": 10},
            "user",
            "ds-status-owner",
            "DeepSearch: a research question",
        )
        refresh_snapshot()
        r = requests.get(
            f"{BASE_URL}/tools/deepsearch/{uid}", headers=_json_headers()
        )
        assert r.status_code == 200, r.text
        body = r.json()
        assert body["uid"] == uid
        assert body["kind"] == "deepsearch"
        assert body["status"] == "pending"
        assert body["query"] == "a research question"
        assert body["ws_url"] == f"/tools/deepsearch/{uid}/ws"
        assert body["session_url"] is None
        assert body["score"] is None
        assert body["page_count"] == 0
    finally:
        _clear()


def test_status_unknown_uid_404(app_server):
    r = requests.get(
        f"{BASE_URL}/tools/deepsearch/nope-not-a-job", headers=_json_headers()
    )
    assert r.status_code == 404


def test_status_rejects_non_deepsearch_kind(app_server):
    try:
        uid = queue.enqueue("other", {}, "user", "ds-kind-owner", "x")
        refresh_snapshot()
        r = requests.get(
            f"{BASE_URL}/tools/deepsearch/{uid}", headers=_json_headers()
        )
        assert r.status_code == 404
    finally:
        get_table("jobs").delete(kind="other")
