from .parsers import QuizParser
from .search import AnswerSearcher
import requests


class QuizSolver:
    """
    Main class for solving quizzes from URLs
    """

    def __init__(self):
        self.parser = QuizParser()
        self.searcher = AnswerSearcher()

    def solve_quiz(self, url):
        """
        Main method to solve quiz from URL

        Args:
            url (str): The URL of the quiz page

        Returns:
            dict: Results containing questions and answers
        """
        try:
            print(f"🔍 Analyzing: {url}")

            # Fetch webpage content
            html_content = self._fetch_url(url)
            if not html_content:
                return {"error": "Could not fetch URL content"}

            # Extract questions
            questions = self.parser.extract_questions(html_content)
            print(f"📝 Found {len(questions)} questions")

            # Find answers for each question
            results = []
            for i, question_data in enumerate(questions, 1):
                print(f"🔎 Solving question {i}/{len(questions)}...")

                answer = self.searcher.find_answer(
                    question_data['question'],
                    question_data.get('options', [])
                )

                results.append({
                    'question_number': i,
                    'question': question_data['question'],
                    'options': question_data.get('options', []),
                    'answer': answer,
                    'type': question_data.get('type', 'unknown')
                })

            return {
                'url': url,
                'total_questions': len(questions),
                'results': results
            }

        except Exception as e:
            return {"error": f"An error occurred: {str(e)}"}

    def _fetch_url(self, url):
        """Fetch content from URL"""
        try:
            response = requests.get(url, timeout=30)
            response.raise_for_status()
            return response.text
        except Exception as e:
            print(f"Error fetching URL: {e}")
            return None

    def solve_multiple_urls(self, urls):
        """Solve quizzes from multiple URLs"""
        all_results = {}
        for url in urls:
            all_results[url] = self.solve_quiz(url)
        return all_results