"""Phase V: Stats service — streak calculation, achievement checks, heatmap data.""" import logging from datetime import date, datetime, timezone from sqlalchemy.ext.asyncio import AsyncSession from sqlmodel import select from ..models.stats import Achievement, DailyCompletion, UserStats logger = logging.getLogger(__name__) ACHIEVEMENT_LABELS = { "on_fire": "🔥 On Fire", "centurion": "💪 Centurion", "speed_runner": "⚡ Speed Runner", "night_owl": "🌙 Night Owl", "planner": "📅 Planner", "consistent": "🎯 Consistent", } ACHIEVEMENT_DESCRIPTIONS = { "on_fire": "7-day consecutive completion streak", "centurion": "Completed 100 tasks", "speed_runner": "5+ tasks completed in a single day", "night_owl": "Completed a task after 10 PM", "planner": "Completed a task before its due date", "consistent": "30-day consecutive completion streak", } async def _get_or_create_stats(session: AsyncSession, user_id: str) -> UserStats: result = await session.execute(select(UserStats).where(UserStats.user_id == user_id)) stats = result.scalar_one_or_none() if not stats: stats = UserStats(user_id=user_id) session.add(stats) await session.flush() return stats async def _upsert_daily_completion(session: AsyncSession, user_id: str, today: date) -> int: result = await session.execute( select(DailyCompletion).where( DailyCompletion.user_id == user_id, DailyCompletion.date == today, ) ) dc = result.scalar_one_or_none() if dc: dc.count += 1 else: dc = DailyCompletion(user_id=user_id, date=today, count=1) session.add(dc) await session.flush() return dc.count async def _unlock_achievement(session: AsyncSession, user_id: str, achievement_type: str) -> bool: result = await session.execute( select(Achievement).where( Achievement.user_id == user_id, Achievement.achievement_type == achievement_type, ) ) if result.scalar_one_or_none(): return False # already unlocked session.add(Achievement(user_id=user_id, achievement_type=achievement_type)) await session.flush() logger.info("Achievement unlocked: user=%s type=%s", user_id, achievement_type) return True async def record_completion( session: AsyncSession, user_id: str, task_id: int, task_data: dict ) -> None: """Record a task completion: update streak, daily count, check achievements.""" today = date.today() now = datetime.now() # Update daily completion count daily_count = await _upsert_daily_completion(session, user_id, today) # Update user stats stats = await _get_or_create_stats(session, user_id) stats.total_completed += 1 if stats.last_active_date is None: stats.current_streak = 1 elif stats.last_active_date == today: pass # already counted today elif (today - stats.last_active_date).days == 1: stats.current_streak += 1 else: stats.current_streak = 1 # streak broken stats.longest_streak = max(stats.current_streak, stats.longest_streak) stats.last_active_date = today stats.updated_at = datetime.utcnow() session.add(stats) # Check achievements if stats.current_streak >= 7: await _unlock_achievement(session, user_id, "on_fire") if stats.current_streak >= 30: await _unlock_achievement(session, user_id, "consistent") if stats.total_completed >= 100: await _unlock_achievement(session, user_id, "centurion") if daily_count >= 5: await _unlock_achievement(session, user_id, "speed_runner") if now.hour >= 22: await _unlock_achievement(session, user_id, "night_owl") if task_data.get("due_date"): try: due = datetime.fromisoformat(task_data["due_date"]) if now < due: await _unlock_achievement(session, user_id, "planner") except (ValueError, TypeError): pass await session.commit() async def get_stats(session: AsyncSession, user_id: str) -> dict: """Return full stats including heatmap data for the last 12 months.""" from datetime import timedelta stats = await _get_or_create_stats(session, user_id) # Heatmap: last 365 days one_year_ago = date.today().replace(year=date.today().year - 1) result = await session.execute( select(DailyCompletion).where( DailyCompletion.user_id == user_id, DailyCompletion.date >= one_year_ago, ) ) completions = result.scalars().all() heatmap = [{"date": str(dc.date), "count": dc.count} for dc in completions] # Achievements ach_result = await session.execute( select(Achievement).where(Achievement.user_id == user_id) ) achievements = [ { "type": a.achievement_type, "label": ACHIEVEMENT_LABELS.get(a.achievement_type, a.achievement_type), "description": ACHIEVEMENT_DESCRIPTIONS.get(a.achievement_type, ""), "unlocked_at": a.unlocked_at.isoformat(), } for a in ach_result.scalars().all() ] return { "total_completed": stats.total_completed, "current_streak": stats.current_streak, "longest_streak": stats.longest_streak, "last_active_date": str(stats.last_active_date) if stats.last_active_date else None, "heatmap": heatmap, "achievements": achievements, } async def get_achievements(session: AsyncSession, user_id: str) -> list: result = await session.execute( select(Achievement).where(Achievement.user_id == user_id) ) return [ { "type": a.achievement_type, "label": ACHIEVEMENT_LABELS.get(a.achievement_type, a.achievement_type), "description": ACHIEVEMENT_DESCRIPTIONS.get(a.achievement_type, ""), "unlocked_at": a.unlocked_at.isoformat(), } for a in result.scalars().all() ]