"""Reddit search enrichment collector.

Enriches existing topics with Reddit engagement data using public JSON API.
"""

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

import requests


class RedditSearchEnricher:
    """Enriches topics with Reddit engagement data."""

    def __init__(self):
        self.name = "reddit_search"
        self.errors: List[str] = []
        self.base_url = "https://old.reddit.com/search.json"
        self.headers = {
            "User-Agent": "TrendingTopicsPipeline/1.0 (by /u/trendbot)"
        }

    def search_topic(self, topic: str) -> Dict[str, Any]:
        """
        Search Reddit for a single topic and extract engagement data.

        Args:
            topic: The topic to search for

        Returns:
            Dictionary with engagement metrics
        """
        try:
            params = {
                "q": topic,
                "sort": "relevance",
                "t": "month",
                "limit": 5
            }
            response = requests.get(
                self.base_url,
                params=params,
                headers=self.headers,
                timeout=15
            )
            response.raise_for_status()

            data = response.json()
            posts = data.get("data", {}).get("children", [])

            if not posts:
                return {
                    "result_count": 0,
                    "total_score": 0,
                    "total_comments": 0,
                    "subreddits": []
                }

            total_score = 0
            total_comments = 0
            subreddits = set()

            for post in posts:
                post_data = post.get("data", {})
                total_score += post_data.get("score", 0)
                total_comments += post_data.get("num_comments", 0)
                subreddit = post_data.get("subreddit", "")
                if subreddit:
                    subreddits.add(subreddit)

            return {
                "result_count": len(posts),
                "total_score": total_score,
                "total_comments": total_comments,
                "subreddits": sorted(list(subreddits))
            }

        except Exception as e:
            self.errors.append(f"{topic}: {str(e)}")
            return {
                "result_count": 0,
                "total_score": 0,
                "total_comments": 0,
                "subreddits": [],
                "error": str(e)
            }

    def enrich(self, topics: List[str]) -> Dict[str, Dict[str, Any]]:
        """
        Enrich a list of topics with Reddit engagement data.

        Args:
            topics: List of topic names to enrich

        Returns:
            Dictionary mapping topic_name -> engagement metrics
        """
        results = {}

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

            # 3-second delay between requests to respect Reddit rate limits
            if i < len(topics) - 1:
                time.sleep(3)

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

        return results
