"""
Usage Examples for Quiz Solver Library

This file contains comprehensive examples of how to use the quiz-solver library.
"""

import sys
import os

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from quiz_solver import QuizSolver
from quiz_solver.parsers import QuizParser
from quiz_solver.search import AnswerSearcher
from quiz_solver.database import AnswerDatabase


def basic_usage_example():
    """
    Example 1: Basic usage with a single URL
    """
    print("=" * 60)
    print("EXAMPLE 1: Basic Usage")
    print("=" * 60)

    solver = QuizSolver()

    # Replace with actual quiz URL
    quiz_url = "https://example.com/quiz"

    try:
        results = solver.solve_quiz(quiz_url)

        if 'error' in results:
            print(f"Error: {results['error']}")
            return

        print(f"Solved {results['total_questions']} questions:")
        for result in results['results']:
            print(f"\nQ{result['question_number']}: {result['question']}")
            if result['options']:
                print("Options:", result['options'])
            print(f"Answer: {result['answer']}")

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


def multiple_urls_example():
    """
    Example 2: Solving multiple quizzes at once
    """
    print("\n" + "=" * 60)
    print("EXAMPLE 2: Multiple URLs")
    print("=" * 60)

    solver = QuizSolver()

    quiz_urls = [
        "https://example.com/quiz1",
        "https://example.com/quiz2",
        "https://example.com/quiz3"
    ]

    all_results = solver.solve_multiple_urls(quiz_urls)

    for url, results in all_results.items():
        print(f"\n📊 Results for {url}:")
        if 'error' in results:
            print(f"   Error: {results['error']}")
        else:
            print(f"   Solved {results['total_questions']} questions")


def custom_parser_example():
    """
    Example 3: Using the parser directly for custom HTML
    """
    print("\n" + "=" * 60)
    print("EXAMPLE 3: Custom Parser Usage")
    print("=" * 60)

    parser = QuizParser()

    # Custom HTML content (could be from a file, database, etc.)
    custom_html = """
    <div class="quiz-container">
        <div class="question">What is the speed of light? A) 299,792 km/s B) 150,000 km/s C) 500,000 km/s</div>
        <div class="question">Who discovered penicillin? A) Marie Curie B) Alexander Fleming C) Albert Einstein</div>
    </div>
    """

    questions = parser.extract_questions(custom_html)
    print(f"Extracted {len(questions)} questions from custom HTML:")

    for i, question in enumerate(questions, 1):
        print(f"\n{i}. {question['question']}")
        if question['options']:
            print("   Options:", question['options'])


def standalone_searcher_example():
    """
    Example 4: Using the answer searcher independently
    """
    print("\n" + "=" * 60)
    print("EXAMPLE 4: Standalone Answer Searcher")
    print("=" * 60)

    searcher = AnswerSearcher()

    # Search for answers to specific questions
    questions_to_search = [
        {
            "question": "What is the capital of Australia?",
            "options": ["A) Sydney", "B) Melbourne", "C) Canberra", "D) Perth"]
        },
        {
            "question": "How many elements are in the periodic table?",
            "options": ["A) 118", "B) 92", "C) 150", "D) 206"]
        }
    ]

    for i, q in enumerate(questions_to_search, 1):
        answer = searcher.find_answer(q["question"], q["options"])
        print(f"\nQ{i}: {q['question']}")
        print(f"Options: {q['options']}")
        print(f"Answer: {answer}")


def database_example():
    """
    Example 5: Using the answer database for caching
    """
    print("\n" + "=" * 60)
    print("EXAMPLE 5: Answer Database Usage")
    print("=" * 60)

    db = AnswerDatabase()

    # Add some answers to the database
    db.add_answer("What is 2+2?", "4")
    db.add_answer("What is the capital of France?", "Paris")

    # Retrieve answers
    answer1 = db.get_answer("What is 2+2?")
    answer2 = db.get_answer("What is the capital of France?")

    print(f"Database answer for 'What is 2+2?': {answer1}")
    print(f"Database answer for 'What is the capital of France?': {answer2}")

    # Search for similar questions
    similar_answer = db.search_similar("What's two plus two?")
    print(f"Similar question match: {similar_answer}")

    # Save the database
    db.save_database()
    print("Database saved successfully!")


def error_handling_example():
    """
    Example 6: Proper error handling
    """
    print("\n" + "=" * 60)
    print("EXAMPLE 6: Error Handling")
    print("=" * 60)

    solver = QuizSolver()

    # Test with invalid URL
    invalid_url = "https://invalid-website-that-does-not-exist-12345.com"
    result = solver.solve_quiz(invalid_url)

    if 'error' in result:
        print(f"Properly handled error: {result['error']}")
        print("✅ Error handling working correctly!")
    else:
        print("Unexpected success with invalid URL")


def integration_example():
    """
    Example 7: Complete integration example
    """
    print("\n" + "=" * 60)
    print("EXAMPLE 7: Complete Integration")
    print("=" * 60)

    # Initialize all components
    solver = QuizSolver()
    db = AnswerDatabase()

    # Example workflow
    quiz_urls = [
        "https://example.com/science-quiz",
        "https://example.com/math-quiz"
    ]

    print("Starting complete quiz solving workflow...")

    for url in quiz_urls:
        print(f"\n🎯 Processing: {url}")

        # Solve quiz
        results = solver.solve_quiz(url)

        if 'error' not in results:
            # Store results in database
            for result in results['results']:
                db.add_answer(result['question'], result['answer'])

            print(f"✅ Completed: {results['total_questions']} questions solved and stored")
        else:
            print(f"❌ Failed: {results['error']}")

    # Save all answers to database
    db.save_database()
    print("\n📊 All answers stored in local database!")


if __name__ == "__main__":
    print("Quiz Solver Library - Usage Examples")
    print("=" * 50)

    # Run all examples
    basic_usage_example()
    multiple_urls_example()
    custom_parser_example()
    standalone_searcher_example()
    database_example()
    error_handling_example()
    integration_example()

    print("\n" + "=" * 60)
    print("🎉 All usage examples completed!")
    print("=" * 60)