from unittest.mock import patch, MagicMock
from juris_base.utils.captcha import poll_task


def test_poll_task_returns_on_ready():
    responses = [
        {"status": "processing"},
        {"status": "ready", "solution": {"gRecaptchaResponse": "token123"}},
    ]
    call_count = 0

    def fake_urlopen(req, timeout):
        nonlocal call_count
        import json
        resp = MagicMock()
        resp.read.return_value = json.dumps(responses[call_count]).encode()
        resp.__enter__ = lambda s: s
        resp.__exit__ = MagicMock(return_value=False)
        call_count += 1
        return resp

    with patch("urllib.request.urlopen", side_effect=fake_urlopen):
        with patch("time.sleep"):
            result = poll_task("api_key", "task_id", max_attempts=5, interval=0)
    assert result == "token123"


def test_poll_task_returns_none_on_failure():
    import json
    resp = MagicMock()
    resp.read.return_value = json.dumps({"status": "failed"}).encode()
    resp.__enter__ = lambda s: s
    resp.__exit__ = MagicMock(return_value=False)

    with patch("urllib.request.urlopen", return_value=resp):
        with patch("time.sleep"):
            result = poll_task("api_key", "task_id", max_attempts=5, interval=0)
    assert result is None
