from __future__ import annotations

from pathlib import Path

import pytest
import requests

from worai.core import find_faq_page_wrong_type as mod


def test_payload_and_curl_generation() -> None:
    payload = mod._build_patch_payload("https://example.com/e", replace_type=False)
    assert payload[0]["op"] == "add"

    payload_replace = mod._build_patch_payload("https://example.com/e", replace_type=True)
    assert payload_replace[0]["op"] == "remove"
    assert payload_replace[1]["op"] == "add"

    curl = mod.generate_curl_command("https://example.com/e", replace_type=True)
    assert "curl -L -X PATCH" in curl
    assert "remove" in curl


def test_patch_entity_success_and_retries(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
    calls: list[dict] = []

    class _Resp:
        status_code = 200

        @staticmethod
        def raise_for_status() -> None:
            return None

    def _ok_patch(url: str, headers: dict, json: list[dict], timeout: int):
        calls.append({"url": url, "headers": headers, "json": json, "timeout": timeout})
        return _Resp()

    monkeypatch.setattr(mod.requests, "patch", _ok_patch)
    mod.patch_entity("https://example.com/e", "wl", replace_type=True)
    assert calls
    assert calls[0]["timeout"] == 15
    assert calls[0]["headers"]["Authorization"] == "Key wl"

    def _fail_patch(*_a, **_k):
        raise requests.exceptions.RequestException("x")

    monkeypatch.setattr(mod.requests, "patch", _fail_patch)
    monkeypatch.setattr(mod.time, "sleep", lambda _s: None)
    mod.patch_entity("https://example.com/e", "wl", replace_type=False)
    out = capsys.readouterr().out
    assert "Giving up" in out


def test_find_entities_and_run_modes(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
    ttl = tmp_path / "data.ttl"
    ttl.write_text(
        """
        @prefix schema: <http://schema.org/> .
        @prefix ex: <https://example.com/> .
        ex:e1 schema:mainEntity ex:o .
        """,
        encoding="utf-8",
    )
    entities = mod.find_entities(str(ttl))
    assert entities == ["https://example.com/e1"]

    monkeypatch.setattr(mod, "find_entities", lambda _p: [])
    assert mod.run(mod.FaqFixOptions(file_path="x.ttl", mode="find")) == []

    monkeypatch.setattr(mod, "find_entities", lambda _p: ["https://example.com/e1"])
    assert mod.run(mod.FaqFixOptions(file_path="x.ttl", mode="find")) == ["https://example.com/e1"]

    mod.run(mod.FaqFixOptions(file_path="x.ttl", mode="dry-run", replace_type=True))
    assert "Sample cURL command" in capsys.readouterr().out

    with pytest.raises(RuntimeError, match="API key required"):
        mod.run(mod.FaqFixOptions(file_path="x.ttl", mode="patch"))

    seen: dict[str, object] = {}
    monkeypatch.setattr(
        mod,
        "patch_entity",
        lambda entity_id, api_key, replace_type=False: seen.update(
            {"entity_id": entity_id, "api_key": api_key, "replace_type": replace_type}
        ),
    )
    mod.run(mod.FaqFixOptions(file_path="x.ttl", mode="patch", api_key="wl", replace_type=True))
    assert seen["api_key"] == "wl"
    assert seen["replace_type"] is True
