from __future__ import annotations

from types import SimpleNamespace

import pytest

from worai.core import wordlift as mod


class _R:
    def __init__(self, status: int = 200, text: str = "ok", payload=None, json_error: bool = False):
        self.status_code = status
        self.text = text
        self._payload = payload if payload is not None else {"data": {"ok": True}}
        self._json_error = json_error

    def json(self):
        if self._json_error:
            raise ValueError("bad")
        return self._payload


def test_graphql_request_error_paths(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(mod.requests, "post", lambda *_a, **_k: _R(status=500, text="err"))
    with pytest.raises(RuntimeError, match="GraphQL HTTP 500"):
        mod.graphql_request("e", "k", "q")

    monkeypatch.setattr(mod.requests, "post", lambda *_a, **_k: _R(json_error=True))
    with pytest.raises(RuntimeError, match="decode GraphQL JSON"):
        mod.graphql_request("e", "k", "q")

    monkeypatch.setattr(mod.requests, "post", lambda *_a, **_k: _R(payload={"errors": ["x"]}))
    with pytest.raises(RuntimeError, match="GraphQL errors"):
        mod.graphql_request("e", "k", "q")


def test_delete_entity_and_delete_entities(monkeypatch: pytest.MonkeyPatch) -> None:
    seen = {"urls": []}

    def _delete(url, headers=None, timeout=60):
        seen["urls"].append(url)
        if "bad" in url:
            return SimpleNamespace(status_code=404)
        return SimpleNamespace(status_code=204)

    monkeypatch.setattr(mod.requests, "delete", _delete)

    assert mod.delete_entity("https://example.com/good", "wl", include_children=True)
    assert not mod.delete_entity("https://example.com/bad", "wl", include_children=False)
    assert any("include_children=true" in u for u in seen["urls"])

    result = mod.delete_entities(["https://example.com/good", "https://example.com/bad"], "wl")
    assert result["https://example.com/good"] is True
    assert result["https://example.com/bad"] is False
