#!/usr/bin/env python3
"""
Command Line Interface for Quiz Solver
"""

import argparse
import sys
import json
from .core import QuizSolver


def main():
    parser = argparse.ArgumentParser(
        description='Solve quizzes from URLs automatically',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  quiz-solver https://example.com/quiz
  quiz-solver https://example.com/quiz --output results.txt
  quiz-solver https://example.com/quiz --format json
        """
    )

    parser.add_argument('url', help='URL of the quiz to solve')
    parser.add_argument('--output', '-o', help='Save results to file')
    parser.add_argument('--format', '-f', choices=['text', 'json'],
                        default='text', help='Output format')
    parser.add_argument('--verbose', '-v', action='store_true',
                        help='Show detailed progress')

    args = parser.parse_args()

    if args.verbose:
        print("🚀 Quiz Solver Starting...")
        print(f"🔍 Analyzing: {args.url}")

    solver = QuizSolver()
    results = solver.solve_quiz(args.url)

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

    if args.format == 'json':
        output = json.dumps(results, indent=2)
    else:
        output = format_text_results(results)

    if args.output:
        with open(args.output, 'w', encoding='utf-8') as f:
            f.write(output)
        if args.verbose:
            print(f"💾 Results saved to: {args.output}")
    else:
        print(output)

    return 0


def format_text_results(results):
    """Format results as readable text"""
    output = []
    output.append(f"🎯 Quiz Solver Results")
    output.append(f"🔗 URL: {results['url']}")
    output.append(f"📊 Total Questions: {results['total_questions']}")
    output.append("=" * 60)

    for result in results['results']:
        output.append(f"\nQ{result['question_number']}: {result['question']}")
        if result['options']:
            output.append("Options:")
            for option in result['options']:
                output.append(f"  {option}")
        output.append(f"✅ Answer: {result['answer']}")
        output.append("-" * 40)

    return "\n".join(output)


if __name__ == "__main__":
    sys.exit(main())