from rights_filter.domain.records import EvidenceSource
from rights_filter.integrations.google_custom_search import (
    GoogleCustomSearchAdapter,
    GoogleCustomSearchClient,
)
from rights_filter.integrations.search_policy import SearchApiPolicy


class FakeJsonTransport:
    def __init__(self, response):
        self.response = response
        self.calls = []

    def request_json(self, method, url, headers=None, payload=None, timeout=10):
        self.calls.append(
            {
                "method": method,
                "url": url,
                "headers": headers or {},
                "payload": payload,
                "timeout": timeout,
            }
        )
        return self.response


class FakeGoogleCustomSearchClient:
    def __init__(self, image_response=None, web_response=None):
        self.image_response = image_response or {"items": []}
        self.web_response = web_response or {"items": []}
        self.image_calls = []
        self.web_calls = []

    def search_image(self, query: str):
        self.image_calls.append(query)
        return self.image_response

    def search_web(self, query: str):
        self.web_calls.append(query)
        return self.web_response


def test_google_custom_search_client_calls_image_search_with_key_and_cx():
    transport = FakeJsonTransport({"items": []})
    client = GoogleCustomSearchClient(
        api_key="google-search-key",
        cx="search-engine-id",
        transport=transport,
        image_num=3,
    )

    client.search_image("IU official profile")

    call = transport.calls[0]
    assert call["method"] == "GET"
    assert call["url"].startswith("https://www.googleapis.com/customsearch/v1?")
    assert "key=google-search-key" in call["url"]
    assert "cx=search-engine-id" in call["url"]
    assert "q=IU+official+profile" in call["url"]
    assert "searchType=image" in call["url"]
    assert "num=3" in call["url"]


def test_google_custom_search_client_merges_configured_image_pages():
    class PagingTransport:
        def __init__(self):
            self.calls = []

        def request_json(self, method, url, headers=None, payload=None, timeout=10):
            self.calls.append({"method": method, "url": url})
            if "start=4" in url:
                return {
                    "items": [
                        {
                            "title": "page 2",
                            "link": "https://example.test/page-2.jpg",
                        }
                    ]
                }
            return {
                "items": [
                    {
                        "title": "page 1",
                        "link": "https://example.test/page-1.jpg",
                    }
                ]
            }

    transport = PagingTransport()
    client = GoogleCustomSearchClient(
        api_key="google-search-key",
        cx="search-engine-id",
        transport=transport,
        image_num=3,
        image_pages=2,
    )

    response = client.search_image("IU official profile")

    assert [item["link"] for item in response["items"]] == [
        "https://example.test/page-1.jpg",
        "https://example.test/page-2.jpg",
    ]
    assert "start=1" in transport.calls[0]["url"]
    assert "start=4" in transport.calls[1]["url"]


def test_google_custom_image_results_are_mapped_as_image_evidence():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            image_response={
                "items": [
                    {
                        "title": "IU official profile",
                        "link": "https://example.test/iu.png",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "image": {
                            "thumbnailLink": "https://example.test/iu-thumb.png",
                            "contextLink": "https://example.test/profile",
                            "height": 900,
                            "width": 700,
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_images("SUB-1", "IU official profile", policy)

    assert evidence[0].source == EvidenceSource.WEB_DETECTION
    assert evidence[0].reason == "Google custom image search result found"
    assert evidence[0].data["provider"] == "google_custom_search"
    assert evidence[0].data["query_signature"] == "google-custom-image:iu official profile"
    assert evidence[0].data["search_type"] == "image"
    assert evidence[0].data["image_url"] == "https://example.test/iu.png"
    assert evidence[0].data["thumbnail_url"] == "https://example.test/iu-thumb.png"
    assert evidence[0].data["result_url"] == "https://example.test/profile"
    assert evidence[0].data["match"] == "search_image"


def test_google_custom_image_results_unwrap_direct_proxy_image_urls():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            image_response={
                "items": [
                    {
                        "title": "IU official profile",
                        "link": (
                            "https://images.example.test/imgres?"
                            "imgurl=cdn.example.test%2Fiu-profile.png"
                            "&amp;imgrefurl=https%3A%2F%2Fexample.test%2Fprofile"
                        ),
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "image": {
                            "thumbnailLink": (
                                "https://images.example.test/thumb?"
                                "image_url=https%3A%2F%2Fcdn.example.test%2Fiu-thumb.jpg"
                            ),
                            "contextLink": "https://example.test/profile?a=1&amp;b=2",
                            "height": 900,
                            "width": 700,
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_images("SUB-1", "IU official profile", policy)

    assert evidence[0].data["image_url"] == "https://cdn.example.test/iu-profile.png"
    assert evidence[0].data["thumbnail_url"] == "https://cdn.example.test/iu-thumb.jpg"
    assert evidence[0].data["result_url"] == "https://example.test/profile?a=1&b=2"


def test_google_custom_image_results_unwrap_weak_proxy_jfif_image_urls():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            image_response={
                "items": [
                    {
                        "title": "IU official profile",
                        "link": (
                            "https://images.example.test/imgres?"
                            "url=https%3A%2F%2Fcdn.example.test%2Fiu-profile.jfif"
                        ),
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "image": {
                            "thumbnailLink": (
                                "https://images.example.test/thumb?"
                                "u=https%3A%2F%2Fcdn.example.test%2Fiu-thumb.jfif"
                            ),
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_images("SUB-1", "IU official profile", policy)

    assert evidence[0].data["image_url"] == "https://cdn.example.test/iu-profile.jfif"
    assert evidence[0].data["thumbnail_url"] == "https://cdn.example.test/iu-thumb.jfif"
    assert evidence[0].data["result_url"] == "https://cdn.example.test/iu-profile.jfif"


def test_google_custom_image_results_unwrap_weak_proxy_query_format_image_urls():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            image_response={
                "items": [
                    {
                        "title": "IU official profile",
                        "link": (
                            "https://images.example.test/imgres?"
                            "url=https%3A%2F%2Fcdn.example.test%2Frender%3Fformat%3Dwebp"
                        ),
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "image": {
                            "thumbnailLink": (
                                "https://images.example.test/thumb?"
                                "u=https%3A%2F%2Fcdn.example.test%2Fthumb%3Ffm%3Djpg"
                            ),
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_images("SUB-1", "IU official profile", policy)

    assert evidence[0].data["image_url"] == "https://cdn.example.test/render?format=webp"
    assert evidence[0].data["thumbnail_url"] == "https://cdn.example.test/thumb?fm=jpg"
    assert evidence[0].data["result_url"] == "https://cdn.example.test/render?format=webp"


def test_google_custom_image_results_unwrap_scheme_less_proxy_query_format_image_urls():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            image_response={
                "items": [
                    {
                        "title": "IU official profile",
                        "link": (
                            "https://images.example.test/imgres?"
                            "url=cdn.example.test%2Frender%3Fformat%3Dwebp"
                        ),
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "image": {
                            "thumbnailLink": (
                                "https://images.example.test/thumb?"
                                "u=cdn.example.test%2Fthumb%3Ffm%3Djpg"
                            ),
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_images("SUB-1", "IU official profile", policy)

    assert evidence[0].data["image_url"] == "https://cdn.example.test/render?format=webp"
    assert evidence[0].data["thumbnail_url"] == "https://cdn.example.test/thumb?fm=jpg"
    assert evidence[0].data["result_url"] == "https://cdn.example.test/render?format=webp"


def test_google_custom_image_results_preserve_pagemap_image_candidates():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            image_response={
                "items": [
                    {
                        "title": "IU official profile",
                        "link": "https://example.test/blocked-original.png",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "image": {
                            "thumbnailLink": "https://example.test/blocked-thumb.png",
                            "contextLink": "https://example.test/profile/page",
                        },
                        "pagemap": {
                            "cse_image": [{"src": "/media/profile-from-page.png"}],
                            "metatags": [{"og:image": "https://cdn.example.test/profile-og.png"}],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_images("SUB-1", "IU official profile", policy)

    assert evidence[0].data["page_image_urls"] == [
        "https://example.test/media/profile-from-page.png",
        "https://cdn.example.test/profile-og.png",
    ]


def test_google_custom_web_results_preserve_page_image_candidates():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": "https://example.test/profile",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "cse_image": [{"src": "https://example.test/page-image.png"}],
                            "metatags": [{"og:image": "https://example.test/og-image.png"}],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].source == EvidenceSource.WEB_DETECTION
    assert evidence[0].reason == "Google custom web search result found"
    assert evidence[0].data["query_signature"] == "google-custom-web:iu official profile"
    assert evidence[0].data["search_type"] == "web"
    assert evidence[0].data["result_url"] == "https://example.test/profile"
    assert evidence[0].data["page_image_urls"] == [
        "https://example.test/page-image.png",
        "https://example.test/og-image.png",
    ]
    assert evidence[0].data["match"] == "page"


def test_google_custom_web_results_unwrap_redirect_result_urls_before_resolving_page_images():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": (
                            "https://www.google.test/url?"
                            "url=https%3A%2F%2Fexample.test%2Fprofiles%2Fiu"
                            "&amp;sa=U"
                        ),
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "cse_image": [{"src": "/media/profile.png"}],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].data["result_url"] == "https://example.test/profiles/iu"
    assert evidence[0].data["page_image_urls"] == [
        "https://example.test/media/profile.png",
    ]


def test_google_custom_web_results_preserve_common_pagemap_image_objects():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": "https://example.test/profile",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "cse_thumbnail": [{"src": "https://example.test/thumb.jpg"}],
                            "imageobject": [
                                {
                                    "url": "https://example.test/image-url.jpg",
                                    "contenturl": "https://example.test/content-url.jpg",
                                    "thumbnailurl": "https://example.test/object-thumb.jpg",
                                }
                            ],
                            "thumbnail": [{"src": "https://example.test/thumb-entry.jpg"}],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].data["page_image_urls"] == [
        "https://example.test/thumb.jpg",
        "https://example.test/image-url.jpg",
        "https://example.test/content-url.jpg",
        "https://example.test/object-thumb.jpg",
        "https://example.test/thumb-entry.jpg",
    ]


def test_google_custom_web_results_ignore_non_image_pagemap_metadata_inside_image_objects():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": "https://example.test/profile",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "imageobject": [
                                {
                                    "url": "https://example.test/image-url.jpg",
                                    "width": "1200",
                                    "height": "900",
                                    "caption": "IU official profile",
                                }
                            ],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].data["page_image_urls"] == [
        "https://example.test/image-url.jpg",
    ]


def test_google_custom_web_results_ignore_non_image_metatag_image_metadata():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": "https://example.test/profile",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "metatags": [
                                {
                                    "og:image": "https://cdn.example.test/profile.jpg",
                                    "og:image:width": "1200",
                                    "og:image:height": "900",
                                    "twitter:image:alt": "IU official profile",
                                }
                            ],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].data["page_image_urls"] == [
        "https://cdn.example.test/profile.jpg",
    ]


def test_google_custom_web_results_preserve_generic_pagemap_image_fields():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": "https://example.test/profile",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "person": [{"image": "https://cdn.example.test/person-profile.jpg"}],
                            "article": [{"url": "https://example.test/plain-page-url"}],
                            "webpage": [
                                {
                                    "primaryimageofpage": {
                                        "url": "/media/primary-profile.jpg",
                                    }
                                }
                            ],
                            "hcard": [{"photo": "https://cdn.example.test/hcard-photo.jpg"}],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].data["page_image_urls"] == [
        "https://cdn.example.test/person-profile.jpg",
        "https://example.test/media/primary-profile.jpg",
        "https://cdn.example.test/hcard-photo.jpg",
    ]


def test_google_custom_web_results_preserve_generic_pagemap_public_url_image_fields():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": "https://example.test/profile",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "webpage": [
                                {
                                    "primaryimageofpage": {
                                        "file": {
                                            "publicUrl": "/media/profile-public-url.png",
                                        },
                                        "canonicalUrl": "https://example.test/not-an-image-page",
                                    }
                                }
                            ],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].data["page_image_urls"] == [
        "https://example.test/media/profile-public-url.png",
    ]


def test_google_custom_web_results_preserve_generic_pagemap_snake_case_url_image_fields():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": "https://example.test/profile",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "webpage": [
                                {
                                    "primaryimageofpage": {
                                        "file": {
                                            "public_url": "/media/profile-snake-public-url.png",
                                        },
                                        "canonical_url": "https://example.test/not-an-image-page",
                                    }
                                }
                            ],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].data["page_image_urls"] == [
        "https://example.test/media/profile-snake-public-url.png",
    ]


def test_google_custom_web_results_preserve_pagemap_srcset_image_candidates():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": "https://example.test/profile",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "webpage": [
                                {
                                    "primaryimageofpage": {
                                        "srcset": (
                                            "/media/profile-small.jpg 320w, "
                                            "/media/profile-large.jpg 1200w"
                                        ),
                                    }
                                }
                            ],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].data["page_image_urls"] == [
        "https://example.test/media/profile-large.jpg",
        "https://example.test/media/profile-small.jpg",
    ]


def test_google_custom_web_results_preserve_pagemap_srcset_urls_with_query_commas():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": "https://example.test/profile",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "webpage": [
                                {
                                    "primaryimageofpage": {
                                        "srcset": (
                                            "https://cdn.example.test/render?img=small,format=webp 320w, "
                                            "https://cdn.example.test/render?img=large,format=webp 1200w"
                                        ),
                                    }
                                }
                            ],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].data["page_image_urls"] == [
        "https://cdn.example.test/render?img=large,format=webp",
        "https://cdn.example.test/render?img=small,format=webp",
    ]


def test_google_custom_web_results_preserve_relative_pagemap_srcset_format_hint_urls():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": "https://example.test/profile",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "webpage": [
                                {
                                    "primaryimageofpage": {
                                        "srcset": (
                                            "render?format=webp&w=320 320w, "
                                            "render?format=webp&w=1200 1200w"
                                        ),
                                    }
                                }
                            ],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].data["page_image_urls"] == [
        "https://example.test/render?format=webp&w=1200",
        "https://example.test/render?format=webp&w=320",
    ]


def test_google_custom_web_results_resolve_relative_pagemap_image_urls_against_result_page():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": "https://example.test/profiles/iu",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "cse_image": [{"src": "/media/profile.png"}],
                            "metatags": [{"og:image": "//cdn.example.test/profile-og.png"}],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].data["page_image_urls"] == [
        "https://example.test/media/profile.png",
        "https://cdn.example.test/profile-og.png",
    ]


def test_google_custom_web_results_unwrap_proxy_pagemap_image_urls():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": "https://example.test/profiles/iu",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "metatags": [
                                {
                                    "og:image": (
                                        "https://images.example.test/imgres?"
                                        "imgurl=https%3A%2F%2Fcdn.example.test%2Fofficial-profile.png"
                                        "&amp;imgrefurl=https%3A%2F%2Fexample.test%2Farticle"
                                    )
                                }
                            ],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].data["page_image_urls"] == [
        "https://cdn.example.test/official-profile.png",
    ]


def test_google_custom_web_results_unwrap_scheme_less_proxy_pagemap_image_urls():
    adapter = GoogleCustomSearchAdapter(
        FakeGoogleCustomSearchClient(
            web_response={
                "items": [
                    {
                        "title": "IU profile page",
                        "link": "https://example.test/profiles/iu",
                        "displayLink": "example.test",
                        "snippet": "profile image",
                        "pagemap": {
                            "metatags": [
                                {
                                    "og:image": (
                                        "https://images.example.test/imgres?"
                                        "imgurl=cdn.example.test%2Fofficial-profile.png"
                                    )
                                }
                            ],
                        },
                    }
                ]
            }
        )
    )
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
    )

    evidence = adapter.search_web_pages("SUB-1", "IU official profile", policy)

    assert evidence[0].data["page_image_urls"] == [
        "https://cdn.example.test/official-profile.png",
    ]


def test_blocked_policy_makes_no_google_custom_search_call():
    client = FakeGoogleCustomSearchClient()
    adapter = GoogleCustomSearchAdapter(client)
    policy = SearchApiPolicy(disabled=True, compliance_approved=True)

    evidence = adapter.search_images("SUB-1", "IU official profile", policy)

    assert client.image_calls == []
    assert evidence[0].source == EvidenceSource.SEARCH_SKIPPED
    assert evidence[0].data["query_signature"] == "google-custom-image:iu official profile"


def test_google_custom_adapter_reserves_configured_page_calls_before_search():
    client = FakeGoogleCustomSearchClient()
    client.image_pages = 2
    adapter = GoogleCustomSearchAdapter(client)
    policy = SearchApiPolicy(
        compliance_approved=True,
        allowed_providers={"google_custom_search"},
        daily_limit=1,
    )

    evidence = adapter.search_images("SUB-1", "IU official profile", policy)

    assert client.image_calls == []
    assert evidence[0].source == EvidenceSource.SEARCH_SKIPPED
    assert evidence[0].reason == "search API usage limit reached"
