# retoor <retoor@molodetz.nl>

from tests.conftest import BASE_URL, login_user
from devplacepy.database import get_table
def _promote_to_admin(username: str) -> None:
    users = get_table("users")
    user = users.find_one(username=username)
    if user:
        users.update({"uid": user["uid"], "role": "Admin"}, ["uid"])


def test_services_data_json(page, seeded_db):
    user = seeded_db["alice"]
    _promote_to_admin(user["username"])
    login_user(page, user)
    page.goto(f"{BASE_URL}/admin/services/data", wait_until="domcontentloaded")
    text = page.inner_text("body > pre") if page.locator("body > pre").count() > 0 else page.content()
    import json

    data = json.loads(text)
    assert "services" in data
    assert isinstance(data["services"], list)


def test_service_detail_unknown_404(page, seeded_db):
    user = seeded_db["alice"]
    _promote_to_admin(user["username"])
    login_user(page, user)
    resp = page.request.get(f"{BASE_URL}/admin/services/nope")
    assert resp.status == 404
    assert page.request.get(f"{BASE_URL}/admin/services/nope/data").status == 404


def test_bots_service_registered_and_opt_in(page, seeded_db):
    user = seeded_db["alice"]
    _promote_to_admin(user["username"])
    login_user(page, user)
    page.goto(f"{BASE_URL}/admin/services", wait_until="domcontentloaded")
    data = page.request.get(f"{BASE_URL}/admin/services/data").json()
    bots = next(s for s in data["services"] if s["name"] == "bots")
    assert bots["enabled"] is False
    assert bots["status"] == "stopped"
    assert "metrics" in bots
    page.goto(f"{BASE_URL}/admin/services/bots", wait_until="domcontentloaded")
    detail = page.locator("[data-service-detail][data-service='bots']")
    assert detail.locator("input[name='bot_fleet_size']").count() == 1
    assert detail.locator("input[name='bot_input_cost_per_1m']").count() == 1
