import pytest

from gsearch_mcp_cli.core.fetcher import validate_url
from gsearch_mcp_cli.exceptions import SSRFBlockedError


class TestValidateUrl:
    def test_accepts_https(self):
        assert validate_url("https://example.com") == "https://example.com"

    def test_accepts_http(self):
        assert validate_url("http://example.com") == "http://example.com"

    def test_rejects_file_scheme(self):
        with pytest.raises(SSRFBlockedError, match="scheme"):
            validate_url("file:///etc/passwd")

    def test_rejects_ftp(self):
        with pytest.raises(SSRFBlockedError, match="scheme"):
            validate_url("ftp://example.com/file")

    def test_rejects_data_uri(self):
        with pytest.raises(SSRFBlockedError, match="scheme"):
            validate_url("data:text/html,<h1>hi</h1>")

    def test_rejects_javascript(self):
        with pytest.raises(SSRFBlockedError, match="scheme"):
            validate_url("javascript:alert(1)")

    def test_rejects_localhost(self):
        with pytest.raises(SSRFBlockedError):
            validate_url("http://localhost")

    def test_rejects_localhost_with_port(self):
        with pytest.raises(SSRFBlockedError):
            validate_url("http://localhost:9222/json")

    def test_rejects_127_0_0_1(self):
        with pytest.raises(SSRFBlockedError):
            validate_url("http://127.0.0.1")

    def test_rejects_10_x(self):
        with pytest.raises(SSRFBlockedError):
            validate_url("http://10.0.0.1")

    def test_rejects_172_16(self):
        with pytest.raises(SSRFBlockedError):
            validate_url("http://172.16.0.1")

    def test_rejects_192_168(self):
        with pytest.raises(SSRFBlockedError):
            validate_url("http://192.168.1.1")

    def test_rejects_metadata_ip(self):
        with pytest.raises(SSRFBlockedError):
            validate_url("http://169.254.169.254")

    def test_rejects_metadata_host(self):
        with pytest.raises(SSRFBlockedError):
            validate_url("http://metadata.google.internal")

    def test_rejects_no_hostname(self):
        with pytest.raises(SSRFBlockedError):
            validate_url("https://")

    def test_rejects_empty(self):
        with pytest.raises(SSRFBlockedError):
            validate_url("")


@pytest.mark.asyncio
async def test_fetch_page_basic():
    """Integration: fetch example.com via httpx."""
    from gsearch_mcp_cli.core.fetcher import fetch_page
    result = await fetch_page("http://example.com", format="text", use_browser="never")
    assert "example" in result.content.lower() or "domain" in result.content.lower()
    assert result.title == "Example Domain"
    assert result.word_count > 0
