# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/google/GSearch.ipynb.

# %% auto 0
__all__ = ['GoogleSearchAuth', 'GoogleSearch']

# %% ../../nbs/google/GSearch.ipynb 2
from typing import List
from dataclasses import dataclass, field
import domolibrary_extensions.google.GAuth as gd
import httpx

from nbdev.showdoc import patch_to

# %% ../../nbs/google/GSearch.ipynb 4
@dataclass
class GoogleSearchAuth(gd.GoogleAuth):
    search_key: str = None
    search_engine_id: str = None
    base_url: str = None

    def __post_init__(self):
        self.base_url = f"https://www.googleapis.com/customsearch/v1?cx={self.search_engine_id}&key={self.search_key}"

    def generate_auth_header(self) -> dict:
        return self.auth_header

# %% ../../nbs/google/GSearch.ipynb 5
@dataclass
class GoogleSearch:
    auth: GoogleSearchAuth = field(repr=False)
    query: str
    is_from_cache: bool
    cnt_results: int
    content: List[dict]
    raw_content: dict = field(repr=False)

    @classmethod
    async def search(
        cls,
        auth: GoogleSearchAuth,
        query: str,
        cache_path: str = None,
        # return_raw: bool = False,
        is_ignore_cache: bool = False,
        debug_api: bool = False,
        client: httpx.AsyncClient = None,
    ):
        res = await gd.get_data(
            url=auth.base_url,
            method="GET",
            cache_path=cache_path,
            debug_api=debug_api,
            params={"q": query},
            is_ignore_cache=is_ignore_cache,
            client=client,
        )

        return cls(
            auth=auth,
            query=query,
            is_from_cache=res.is_from_cache,
            cnt_results=len(res.response["items"]),
            raw_content=res.response,
            content=res.response["items"],
        )
