File size: 3,215 Bytes
5af4179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# 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.")