from googlesearch import search
import requests
import re


class AnswerSearcher:
    """
    Search for answers using Google search
    """

    def __init__(self):
        self.cache = {}

    def find_answer(self, question, options=None):
        """Find answer using Google search"""
        try:
            # Check cache first
            cache_key = question + str(options)
            if cache_key in self.cache:
                return self.cache[cache_key]

            search_query = self._build_search_query(question, options)
            results = list(search(search_query, num_results=5))

            # Analyze results for answers
            best_answer = self._analyze_results(results, question, options)

            # Cache the result
            self.cache[cache_key] = best_answer
            return best_answer

        except Exception as e:
            return f"Error searching: {str(e)}"

    def _build_search_query(self, question, options):
        """Build effective search query"""
        query = f'"{question}"'

        if options:
            # Add options to search query
            options_text = " ".join(options[:3])
            query += f" {options_text}"

        query += " answer"
        return query

    def _analyze_results(self, results, question, options):
        """Analyze search results to find the best answer"""
        answer_counts = {}

        for url in results[:3]:  # Check first 3 results
            try:
                page_content = self._fetch_page_content(url)
                potential_answers = self._extract_potential_answers(page_content, question, options)

                for answer in potential_answers:
                    answer_counts[answer] = answer_counts.get(answer, 0) + 1
            except:
                continue

        if answer_counts:
            # Return most frequent answer
            best_answer = max(answer_counts.items(), key=lambda x: x[1])
            return best_answer[0]

        return "Answer not found"

    def _fetch_page_content(self, url):
        """Fetch content from URL"""
        try:
            response = requests.get(url, timeout=10)
            return response.text
        except:
            return ""

    def _extract_potential_answers(self, content, question, options):
        """Extract potential answers from page content"""
        answers = []

        # Look for exact matches with options
        if options:
            for option in options:
                option_text = re.sub(r'^[A-D]\)\s*', '', option)  # Remove A), B) prefix
                if option_text.lower() in content.lower():
                    answers.append(option)

        # Look for answer patterns
        answer_patterns = [
            r'answer[^.]*?is[^.]*?([A-D])',
            r'correct.*?option.*?([A-D])',
            r'([A-D]).*?correct',
        ]

        for pattern in answer_patterns:
            matches = re.findall(pattern, content, re.IGNORECASE)
            for match in matches:
                # Map back to full option text
                if options and match in ['A', 'B', 'C', 'D']:
                    option_index = ord(match) - ord('A')
                    if option_index < len(options):
                        answers.append(options[option_index])

        return answers