import pytest
import requests

_DETECT_TIMEOUT = 60


def test_nft_res_01_loader_outage_after_init(
    warm_engine, http_client, mock_loader_url, image_small
):
    requests.post(
        f"{mock_loader_url}/mock/config", json={"mode": "error"}, timeout=10
    ).raise_for_status()
    files = {"file": ("r1.jpg", image_small, "image/jpeg")}
    r = http_client.post("/detect", files=files, timeout=_DETECT_TIMEOUT)
    assert r.status_code == 200
    assert isinstance(r.json(), list)
    h = http_client.get("/health")
    assert h.status_code == 200
    hd = h.json()
    assert hd["status"] == "healthy"
    assert hd.get("errorMessage") is None


def test_nft_res_03_transient_loader_first_fail(
    mock_loader_url, http_client, image_small
):
    requests.post(
        f"{mock_loader_url}/mock/config", json={"mode": "first_fail"}, timeout=10
    ).raise_for_status()
    files = {"file": ("r3a.jpg", image_small, "image/jpeg")}
    r1 = http_client.post("/detect", files=files, timeout=_DETECT_TIMEOUT)
    files2 = {"file": ("r3b.jpg", image_small, "image/jpeg")}
    r2 = http_client.post("/detect", files=files2, timeout=_DETECT_TIMEOUT)
    assert r2.status_code == 200
    if r1.status_code != 200:
        assert r1.status_code != 500


