# utils/challenge_manager.py import json import os import uuid from datetime import datetime from typing import Dict, List, Optional CHALLENGES_FILE = "data/challenges.json" def _load_challenges() -> Dict: """Loads all challenges from the JSON file.""" if os.path.exists(CHALLENGES_FILE): with open(CHALLENGES_FILE, "r") as f: try: return json.load(f) except json.JSONDecodeError: return {} return {} def _save_challenges(challenges: Dict): """Saves all challenges to the JSON file.""" os.makedirs(os.path.dirname(CHALLENGES_FILE), exist_ok=True) with open(CHALLENGES_FILE, "w") as f: json.dump(challenges, f, indent=2) class ChallengeManager: def __init__(self): self.challenges = _load_challenges() def create_challenge(self, creator_id: str, topic: str, difficulty: str, num_questions: int) -> str: """Creates a new challenge and returns its ID.""" challenge_id = str(uuid.uuid4())[:8] # Short UUID for easy sharing challenge_data = { "challenge_id": challenge_id, "creator_id": creator_id, "created_at": datetime.now().isoformat(), "topic": topic, "difficulty": difficulty, "num_questions": num_questions, "participants": {}, # {user_id: {score: int, quiz_results: List}} "status": "active" # active, completed } self.challenges[challenge_id] = challenge_data _save_challenges(self.challenges) return challenge_id def get_challenge(self, challenge_id: str) -> Optional[Dict]: """Retrieves a challenge by its ID.""" return self.challenges.get(challenge_id) def update_challenge_score(self, challenge_id: str, user_id: str, score: int, quiz_results: List[Dict]): """Updates a participant's score and quiz results for a challenge.""" challenge = self.challenges.get(challenge_id) if challenge: challenge["participants"][user_id] = { "score": score, "quiz_results": quiz_results, "completed_at": datetime.now().isoformat() } _save_challenges(self.challenges) else: raise ValueError(f"Challenge with ID {challenge_id} not found.") def get_all_active_challenges(self) -> List[Dict]: """Returns a list of all active challenges.""" return [c for c in self.challenges.values() if c.get("status") == "active"] def get_challenges_by_creator(self, creator_id: str) -> List[Dict]: """Returns a list of challenges created by a specific user.""" return [c for c in self.challenges.values() if c.get("creator_id") == creator_id] def set_challenge_status(self, challenge_id: str, status: str): """Sets the status of a challenge.""" if challenge_id in self.challenges: self.challenges[challenge_id]["status"] = status _save_challenges(self.challenges) else: raise ValueError(f"Challenge with ID {challenge_id} not found.")