""" Action Tracking System for TRuCAL Tracks user actions, achievements, and progress through the experience. """ from typing import Dict, List, Optional, Any, Set, Tuple from dataclasses import dataclass, field from datetime import datetime, timedelta import json import os from enum import Enum import uuid from .purpose_assessment import PurposeDimension class ActionType(str, Enum): """Types of actions that can be tracked""" REALM_ACTION = "realm_action" PURPOSE_ACTION = "purpose_action" ACHIEVEMENT = "achievement" MILESTONE = "milestone" DAILY = "daily" WEEKLY = "weekly" CHALLENGE = "challenge" class ActionStatus(str, Enum): """Possible statuses for an action""" PENDING = "pending" IN_PROGRESS = "in_progress" COMPLETED = "completed" FAILED = "failed" ABANDONED = "abandoned" @dataclass class ActionDefinition: """Definition of a trackable action""" id: str name: str description: str action_type: ActionType purpose_dimensions: List[PurposeDimension] xp_reward: int = 0 cooldown: Optional[timedelta] = None prerequisites: List[str] = field(default_factory=list) # IDs of required actions repeatable: bool = False max_repeats: Optional[int] = None hidden: bool = False metadata: Dict[str, Any] = field(default_factory=dict) @dataclass class ActionInstance: """A specific instance of a user taking an action""" id: str action_id: str user_id: str status: ActionStatus = ActionStatus.PENDING start_time: Optional[datetime] = None end_time: Optional[datetime] = None progress: float = 0.0 # 0.0 to 1.0 data: Dict[str, Any] = field(default_factory=dict) # Any additional data created_at: datetime = field(default_factory=datetime.utcnow) updated_at: datetime = field(default_factory=datetime.utcnow) class ActionTracker: """Tracks user actions and achievements""" def __init__(self, storage_path: Optional[str] = None): self.actions: Dict[str, ActionDefinition] = {} self.action_instances: Dict[str, Dict[str, List[ActionInstance]]] = {} # user_id -> action_id -> [instances] self.completed_actions: Dict[str, Set[str]] = {} # user_id -> set of completed action IDs self.storage_path = storage_path # Load default actions and achievements self._load_default_actions() # Load existing data if storage path is provided if storage_path and os.path.exists(storage_path): self.load_data() def _load_default_actions(self) -> None: """Load default action definitions""" self.actions = { # Daily actions 'daily_reflection': ActionDefinition( id='daily_reflection', name='Daily Reflection', description='Spend a few moments reflecting on your day', action_type=ActionType.DAILY, purpose_dimensions=[PurposeDimension.GROWTH, PurposeDimension.SELF_EXPRESSION], xp_reward=20, cooldown=timedelta(hours=20), # Allow some flexibility in timing repeatable=True ), 'daily_goal_setting': ActionDefinition( id='daily_goal_setting', name='Set Daily Intentions', description='Set your intentions for the day', action_type=ActionType.DAILY, purpose_dimensions=[PurposeDimension.GROWTH, PurposeDimension.MASTERY], xp_reward=15, cooldown=timedelta(hours=20), repeatable=True ), # Purpose-aligned actions 'express_gratitude': ActionDefinition( id='express_gratitude', name='Express Gratitude', description='Express gratitude for something or someone', action_type=ActionType.PURPOSE_ACTION, purpose_dimensions=[PurposeDimension.COMPASSION, PurposeDimension.HARMONY], xp_reward=30 ), 'help_others': ActionDefinition( id='help_others', name='Help Someone', description='Offer help or support to someone in need', action_type=ActionType.PURPOSE_ACTION, purpose_dimensions=[PurposeDimension.COMPASSION, PurposeDimension.COMMUNITY], xp_reward=50 ), 'learn_new_skill': ActionDefinition( id='learn_new_skill', name='Learn Something New', description='Spend time learning a new skill or concept', action_type=ActionType.PURPOSE_ACTION, purpose_dimensions=[PurposeDimension.GROWTH, PurposeDimension.MASTERY], xp_reward=40 ), 'stand_up_for_justice': ActionDefinition( id='stand_up_for_justice', name='Stand Up for Justice', description='Take action to support a cause you believe in', action_type=ActionType.PURPOSE_ACTION, purpose_dimensions=[PurposeDimension.JUSTICE, PurposeDimension.COMMUNITY], xp_reward=60 ), # Milestones 'first_action': ActionDefinition( id='first_action', name='First Step', description='Complete your first action', action_type=ActionType.MILESTONE, purpose_dimensions=[], xp_reward=100, hidden=True ), 'purpose_aligned_week': ActionDefinition( id='purpose_aligned_week', name='Purposeful Week', description='Complete purpose-aligned actions for 7 days in a row', action_type=ActionType.MILESTONE, purpose_dimensions=[], xp_reward=200, prerequisites=['first_action'] ) } def load_data(self) -> None: """Load action tracking data from disk""" if not self.storage_path or not os.path.exists(self.storage_path): return try: with open(self.storage_path, 'r') as f: data = json.load(f) # Load action instances self.action_instances = { user_id: { action_id: [ ActionInstance( id=inst['id'], action_id=inst['action_id'], user_id=inst['user_id'], status=ActionStatus(inst['status']), start_time=datetime.fromisoformat(inst['start_time']) if inst.get('start_time') else None, end_time=datetime.fromisoformat(inst['end_time']) if inst.get('end_time') else None, progress=inst.get('progress', 0.0), data=inst.get('data', {}), created_at=datetime.fromisoformat(inst['created_at']), updated_at=datetime.fromisoformat(inst['updated_at']) ) for inst in instances ] for action_id, instances in user_actions.items() } for user_id, user_actions in data.get('action_instances', {}).items() } # Load completed actions self.completed_actions = { user_id: set(actions) for user_id, actions in data.get('completed_actions', {}).items() } except Exception as e: print(f"Error loading action tracking data: {e}") def save_data(self) -> None: """Save action tracking data to disk""" if not self.storage_path: return try: # Create directory if it doesn't exist os.makedirs(os.path.dirname(os.path.abspath(self.storage_path)), exist_ok=True) # Prepare data for serialization data = { 'action_instances': { user_id: { action_id: [ { 'id': inst.id, 'action_id': inst.action_id, 'user_id': inst.user_id, 'status': inst.status.value, 'start_time': inst.start_time.isoformat() if inst.start_time else None, 'end_time': inst.end_time.isoformat() if inst.end_time else None, 'progress': inst.progress, 'data': inst.data, 'created_at': inst.created_at.isoformat(), 'updated_at': inst.updated_at.isoformat() } for inst in instances ] for action_id, instances in user_actions.items() } for user_id, user_actions in self.action_instances.items() }, 'completed_actions': { user_id: list(actions) for user_id, actions in self.completed_actions.items() } } with open(self.storage_path, 'w') as f: json.dump(data, f, indent=2) except Exception as e: print(f"Error saving action tracking data: {e}") def start_action(self, user_id: str, action_id: str, data: Optional[Dict[str, Any]] = None) -> Optional[ActionInstance]: """Start a new action instance""" if action_id not in self.actions: return None action_def = self.actions[action_id] now = datetime.utcnow() # Check if action is on cooldown if not self._can_perform_action(user_id, action_id): return None # Check prerequisites if not self._check_prerequisites(user_id, action_def): return None # Create new action instance instance = ActionInstance( id=str(uuid.uuid4()), action_id=action_id, user_id=user_id, status=ActionStatus.IN_PROGRESS, start_time=now, data=data or {}, updated_at=now ) # Store the instance if user_id not in self.action_instances: self.action_instances[user_id] = {} if action_id not in self.action_instances[user_id]: self.action_instances[user_id][action_id] = [] self.action_instances[user_id][action_id].append(instance) # Save data if storage path is configured if self.storage_path: self.save_data() return instance def complete_action(self, user_id: str, action_id: str, data: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]: """Mark an action as completed""" if user_id not in self.action_instances or action_id not in self.action_instances[user_id]: return None # Find the most recent in-progress instance instances = self.action_instances[user_id][action_id] instance = next((i for i in reversed(instances) if i.status == ActionStatus.IN_PROGRESS), None) if not instance: return None # Update instance now = datetime.utcnow() instance.status = ActionStatus.COMPLETED instance.end_time = now instance.progress = 1.0 instance.updated_at = now if data: instance.data.update(data) # Update completed actions if user_id not in self.completed_actions: self.completed_actions[user_id] = set() self.completed_actions[user_id].add(action_id) # Get action definition action_def = self.actions.get(action_id) xp_reward = action_def.xp_reward if action_def else 0 # Check for any achievements or unlocks unlocks = self._check_achievements(user_id) # Save data if storage path is configured if self.storage_path: self.save_data() return { 'success': True, 'action_id': action_id, 'instance_id': instance.id, 'xp_earned': xp_reward, 'unlocks': unlocks } def _can_perform_action(self, user_id: str, action_id: str) -> bool: """Check if a user can perform an action (cooldown, etc.)""" action_def = self.actions.get(action_id) if not action_def: return False # Check cooldown if action_def.cooldown and user_id in self.action_instances and action_id in self.action_instances[user_id]: last_instance = next( (i for i in reversed(self.action_instances[user_id][action_id]) if i.status == ActionStatus.COMPLETED), None ) if last_instance and last_instance.end_time: time_since_last = datetime.utcnow() - last_instance.end_time if time_since_last < action_def.cooldown: return False # Check max repeats if not action_def.repeatable and action_id in self.completed_actions.get(user_id, set()): return False if action_def.max_repeats and action_id in self.action_instances.get(user_id, {}): completed_count = sum( 1 for i in self.action_instances[user_id][action_id] if i.status == ActionStatus.COMPLETED ) if completed_count >= action_def.max_repeats: return False return True def _check_prerequisites(self, user_id: str, action_def: ActionDefinition) -> bool: """Check if a user meets all prerequisites for an action""" if not action_def.prerequisites: return True completed = self.completed_actions.get(user_id, set()) return all(prereq in completed for prereq in action_def.prerequisites) def _check_achievements(self, user_id: str) -> List[Dict[str, Any]]: """Check for any achievements or unlocks based on completed actions""" unlocks = [] # Check for first action achievement if 'first_action' not in self.completed_actions.get(user_id, set()) and \ any(i.status == ActionStatus.COMPLETED for instances in self.action_instances.get(user_id, {}).values() for i in instances): self.complete_action(user_id, 'first_action') unlocks.append({ 'type': 'achievement', 'id': 'first_action', 'name': 'First Step', 'description': 'You\'ve taken your first action!', 'xp_reward': self.actions['first_action'].xp_reward }) # Check for purpose-aligned week achievement if 'first_action' in self.completed_actions.get(user_id, set()) and \ 'purpose_aligned_week' not in self.completed_actions.get(user_id, set()): # Check for 7 days of purpose-aligned actions # This is a simplified check - in a real implementation, you'd want to check # for actions on 7 consecutive days purpose_action_count = sum( 1 for action_id in self.completed_actions.get(user_id, set()) if action_id in self.actions and any(dim in [PurposeDimension.GROWTH, PurposeDimension.COMMUNITY, PurposeDimension.JUSTICE, PurposeDimension.COMPASSION] for dim in self.actions[action_id].purpose_dimensions) ) if purpose_action_count >= 7: self.complete_action(user_id, 'purpose_aligned_week') unlocks.append({ 'type': 'achievement', 'id': 'purpose_aligned_week', 'name': 'Purposeful Week', 'description': 'You\'ve completed purpose-aligned actions for 7 days!', 'xp_reward': self.actions['purpose_aligned_week'].xp_reward }) return unlocks def get_user_progress(self, user_id: str) -> Dict[str, Any]: """Get a summary of a user's progress and achievements""" completed = self.completed_actions.get(user_id, set()) total_actions = len([a for a in self.actions.values() if not a.hidden]) # Calculate XP total xp_total = sum( self.actions[action_id].xp_reward for action_id in completed if action_id in self.actions ) # Get recent activity recent_activity = [] if user_id in self.action_instances: all_instances = [ instance for action_instances in self.action_instances[user_id].values() for instance in action_instances if instance.status == ActionStatus.COMPLETED ] recent_activity = sorted( all_instances, key=lambda x: x.end_time or x.updated_at, reverse=True )[:10] # Last 10 completed actions # Get available actions (not completed or repeatable) available_actions = [ action for action_id, action in self.actions.items() if not action.hidden and (action_id not in completed or action.repeatable) and self._check_prerequisites(user_id, action) and self._can_perform_action(user_id, action_id) ] return { 'completed_actions': len(completed), 'total_actions': total_actions, 'xp_total': xp_total, 'level': (xp_total // 1000) + 1, # Simple leveling: 1000 XP per level 'recent_activity': [ { 'action_id': i.action_id, 'action_name': self.actions[i.action_id].name if i.action_id in self.actions else 'Unknown', 'completed_at': i.end_time.isoformat() if i.end_time else None, 'xp_earned': self.actions[i.action_id].xp_reward if i.action_id in self.actions else 0 } for i in recent_activity ], 'available_actions': [ { 'id': a.id, 'name': a.name, 'description': a.description, 'xp_reward': a.xp_reward, 'purpose_dimensions': [d.value for d in a.purpose_dimensions] } for a in available_actions ] }