"""Google Autocomplete enrichment collector.

Enriches existing topics with autocomplete suggestions from Google.
"""

import time
import urllib.parse
from typing import List, Dict

import requests


class GoogleAutocompleteEnricher:
    """Enriches topics with Google autocomplete suggestions."""

    def __init__(self):
        self.name = "google_autocomplete"
        self.errors: List[str] = []
        self.base_url = "http://suggestqueries.google.com/complete/search"

    def get_suggestions(self, topic: str) -> List[str]:
        """
        Get autocomplete suggestions for a single topic.

        Args:
            topic: The topic to get suggestions for

        Returns:
            List of autocomplete suggestions
        """
        try:
            params = {
                "client": "firefox",
                "q": topic
            }
            response = requests.get(
                self.base_url,
                params=params,
                timeout=10
            )
            response.raise_for_status()

            # Response is JSON array: [query, [suggestions]]
            data = response.json()
            if isinstance(data, list) and len(data) >= 2:
                return data[1]
            return []

        except Exception as e:
            self.errors.append(f"{topic}: {str(e)}")
            return []

    def enrich(self, topics: List[str]) -> Dict[str, List[str]]:
        """
        Enrich a list of topics with autocomplete suggestions.

        Args:
            topics: List of topic names to enrich

        Returns:
            Dictionary mapping topic_name -> list of suggestions
        """
        results = {}

        for i, topic in enumerate(topics):
            suggestions = self.get_suggestions(topic)
            results[topic] = suggestions

            # 1-second delay between requests to avoid rate limiting
            if i < len(topics) - 1:
                time.sleep(1)

            # Progress indicator every 10 topics
            if (i + 1) % 10 == 0:
                print(f"    Autocomplete: {i + 1}/{len(topics)} topics processed")

        return results
