from __future__ import annotations

import pytest

responses = pytest.importorskip("responses")

from scrape_forvo.errors import ForvoBlockedError
from scrape_forvo.fetch import fetch_html_requests, make_session


@responses.activate
def test_fetch_html_requests_sets_referer_and_warmup() -> None:
    session = make_session()
    homepage = "https://forvo.com/"
    target = "https://forvo.com/search/egg/no/"

    responses.add(responses.GET, homepage, body="ok", status=200)
    responses.add(responses.GET, target, body="<html>ok</html>", status=200)

    html = fetch_html_requests(target, session)
    assert html == "<html>ok</html>"

    called_urls = [call.request.url for call in responses.calls]
    assert homepage in called_urls
    assert target in called_urls

    target_call = next(call for call in responses.calls if call.request.url == target)
    assert target_call.request.headers.get("Referer") == homepage


@responses.activate
def test_fetch_html_requests_403_raises() -> None:
    session = make_session()
    target = "https://forvo.com/search/egg/no/"

    responses.add(responses.GET, "https://forvo.com/", body="ok", status=200)
    responses.add(responses.GET, target, body="nope", status=403)

    try:
        fetch_html_requests(target, session)
    except ForvoBlockedError as exc:
        assert "HTTP 403" in str(exc)
    else:
        raise AssertionError("Expected ForvoBlockedError")
