import requests
import json
from .search_api import SearchAPI


class GoogleSearch(SearchAPI):
    def __init__(
        self,
        api_key="6768f07860d06f6207f5e008",
        advanced_search=True,
        country="us",
        language="en",
        results=10,
    ):
        """
        Initialize the GoogleSearch client.

        :param api_key: Your personal API key from Scrapingdog.
        :param advanced_search: Whether to use advanced features (costs 20 credits if True).
        :param country: The ISO country code for localized Google results.
        :param language: The language code for results (e.g. "en", "es").
        :param results: Number of results to return (1-100).
        """
        super().__init__()  # Initialize the base class
        self.api_key = api_key
        self.advanced_search = "true" if advanced_search else "false"
        self.country = country
        self.language = language
        self.results = results
        self.base_url = "https://api.scrapingdog.com/google"

    def retrieve_query(self, text_query, k=10, page=0):
        """
        Retrieves top-k results from the Scrapingdog Google Search API.

        :param query_features: The dictionary returned by compute_query (holding the query).
        :param k: Number of results to return (max 100). This will override the default if needed.
        :param page: The page number of Google search results (0-based).

        :return: (list_of_results, list_of_distances)
                 For demonstration, we return a list of metadata and a mock list_of_distances.
        """

        formatted_ref = ""
        params = {
            "api_key": self.api_key,
            "query": text_query,
            "results": min(k, 100),  # ensure we do not exceed max 100
            "advance_search": self.advanced_search,
            "country": self.country,
            "language": self.language,
            "page": page,
        }

        try:
            response = requests.get(self.base_url, params=params)
            response.raise_for_status()  # Raise an exception for bad status codes (4xx or 5xx)

            if response.status_code == 200:
                data = response.json()
                if "answer_box" in data:
                    formatted_ref += (
                        f"Passage #0 Title: {data['answer_box'].get('title', 'N/A')}\n"
                    )
                    formatted_ref += (
                        f"Passage #0 Text: {data['answer_box'].get('snippet', 'N/A')}\n"
                    )
                organic_data = data.get("organic_results", [])
                for i, item in enumerate(organic_data):
                    passage_index = i + 1 if "answer_box" in data else i
                    formatted_ref += (
                        f"Passage #{passage_index} Title: {item.get('title', 'N/A')}\n"
                    )
                    if "snippet" in item:
                        formatted_ref += f"Passage #{passage_index} Text: {item.get('snippet', 'N/A')}\n"
            return formatted_ref
        except requests.exceptions.SSLError:
            return ""
        except requests.exceptions.RequestException as e:
            return ""
