All files / web/src/hooks useSessionPlan.ts

0% Statements 0/673
0% Branches 0/1
0% Functions 0/1
0% Lines 0/673

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
'use client'

import { useCallback, useEffect, useRef, useState } from 'react'
import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
import type { SessionPlan, SlotResult, GameBreakSettings } from '@/db/schema/session-plans'
import type { GameResultsReport } from '@/lib/arcade/game-sdk/types'
import type { ProblemGenerationMode } from '@/lib/curriculum/config'
import type { SessionFlowEvent } from '@/lib/curriculum/session-flow'
import type { SessionMode } from '@/lib/curriculum/session-mode'
import { api } from '@/lib/queryClient'
import { sessionPlanKeys } from '@/lib/queryKeys'
import { useBackgroundTask } from './useBackgroundTask'

// Re-export query keys for consumers
export { sessionPlanKeys } from '@/lib/queryKeys'

// ============================================================================
// API Functions
// ============================================================================

async function fetchActiveSessionPlan(playerId: string): Promise<SessionPlan | null> {
  const res = await api(`curriculum/${playerId}/sessions/plans`)
  if (!res.ok) throw new Error('Failed to fetch active session plan')
  const data = await res.json()
  return data.plan ?? null
}

/**
 * Error thrown when trying to generate a plan but one already exists.
 * Contains the existing plan so callers can recover.
 */
export class ActiveSessionExistsClientError extends Error {
  constructor(public readonly existingPlan: SessionPlan) {
    super('Active session already exists')
    this.name = 'ActiveSessionExistsClientError'
  }
}

/**
 * Error thrown when trying to generate a plan but no skills are enabled.
 */
export class NoSkillsEnabledClientError extends Error {
  constructor(message: string) {
    super(message)
    this.name = 'NoSkillsEnabledClientError'
  }
}

/**
 * Error thrown when the weekly session limit is reached (free tier).
 */
export class SessionLimitReachedError extends Error {
  constructor(
    public readonly limit: number,
    public readonly count: number
  ) {
    super(`Weekly session limit reached (${count}/${limit})`)
    this.name = 'SessionLimitReachedError'
  }
}

/**
 * Which session parts to include
 */
interface EnabledParts {
  abacus: boolean
  visualization: boolean
  linear: boolean
}

/** Parameters for generating a session plan */
interface GenerateSessionPlanParams {
  playerId: string
  durationMinutes: number
  abacusTermCount?: { min: number; max: number }
  enabledParts?: EnabledParts
  partTimeWeights?: { abacus: number; visualization: number; linear: number }
  purposeTimeWeights?: { focus: number; reinforce: number; review: number; challenge: number }
  shufflePurposes?: boolean
  problemGenerationMode?: ProblemGenerationMode
  confidenceThreshold?: number
  sessionMode?: SessionMode
  gameBreakSettings?: GameBreakSettings
  comfortAdjustment?: number
}

/**
 * Create a background task for session plan generation.
 * Returns the task ID — subscribe via useBackgroundTask for progress.
 */
async function createSessionPlanTask(params: GenerateSessionPlanParams): Promise<string> {
  const res = await api(`curriculum/${params.playerId}/sessions/plans`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      durationMinutes: params.durationMinutes,
      abacusTermCount: params.abacusTermCount,
      enabledParts: params.enabledParts,
      partTimeWeights: params.partTimeWeights,
      purposeTimeWeights: params.purposeTimeWeights,
      shufflePurposes: params.shufflePurposes,
      problemGenerationMode: params.problemGenerationMode,
      confidenceThreshold: params.confidenceThreshold,
      sessionMode: params.sessionMode,
      gameBreakSettings: params.gameBreakSettings,
      comfortAdjustment: params.comfortAdjustment,
    }),
  })
  if (!res.ok) {
    const errorData = await res.json().catch(() => ({}))

    // Handle 409 conflict - active session exists
    if (
      res.status === 409 &&
      errorData.code === 'ACTIVE_SESSION_EXISTS' &&
      errorData.existingPlan
    ) {
      throw new ActiveSessionExistsClientError(errorData.existingPlan)
    }

    // Handle 400 - no skills enabled
    if (res.status === 400 && errorData.code === 'NO_SKILLS_ENABLED') {
      throw new NoSkillsEnabledClientError(errorData.error)
    }

    // Handle 403 - session limit reached (free tier)
    if (res.status === 403 && errorData.code === 'SESSION_LIMIT_REACHED') {
      throw new SessionLimitReachedError(errorData.limit, errorData.count)
    }

    throw new Error(errorData.error || 'Failed to generate session plan')
  }
  const data = await res.json()
  return data.taskId
}

async function updateSessionPlan({
  playerId,
  planId,
  action,
  result,
  reason,
  breakFinishReason,
}: {
  playerId: string
  planId: string
  action:
    | 'approve'
    | 'start'
    | 'record'
    | 'end_early'
    | 'abandon'
    | 'part_transition_complete'
    | 'break_finished'
    | 'break_results_acked'
  result?: Omit<SlotResult, 'timestamp' | 'partNumber'>
  reason?: string
  breakFinishReason?: 'timeout' | 'gameFinished' | 'skipped'
}): Promise<SessionPlan> {
  const res = await api(`curriculum/${playerId}/sessions/plans/${planId}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ action, result, reason, breakFinishReason }),
  })
  if (!res.ok) {
    const error = await res.json().catch(() => ({}))
    throw new Error(error.error || `Failed to ${action} session plan`)
  }
  const data = await res.json()
  return data.plan
}

async function applySessionFlowEvent({
  playerId,
  planId,
  event,
  expectedFlowVersion,
}: {
  playerId: string
  planId: string
  event: SessionFlowEvent
  expectedFlowVersion?: number
}): Promise<SessionPlan> {
  const res = await api(`curriculum/${playerId}/sessions/plans/${planId}/flow-events`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ event, expectedFlowVersion }),
  })
  if (!res.ok) {
    const error = await res.json().catch(() => ({}))
    throw new Error(error.error || `Failed to apply flow event: ${event.type}`)
  }
  const data = await res.json()
  return data.plan
}

/**
 * Context for recording a redo result
 */
export interface RedoContext {
  /** Part index of the problem being redone */
  originalPartIndex: number
  /** Slot index of the problem being redone */
  originalSlotIndex: number
  /** Whether the original answer was correct (affects recording logic) */
  originalWasCorrect: boolean
}

async function recordRedoResult({
  playerId,
  planId,
  result,
  redoContext,
}: {
  playerId: string
  planId: string
  result: Omit<SlotResult, 'timestamp' | 'partNumber'>
  redoContext: RedoContext
}): Promise<SessionPlan> {
  const res = await api(`curriculum/${playerId}/sessions/plans/${planId}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ action: 'record_redo', result, redoContext }),
  })
  if (!res.ok) {
    const error = await res.json().catch(() => ({}))
    throw new Error(error.error || 'Failed to record redo result')
  }
  const data = await res.json()
  return data.plan
}

// ============================================================================
// Hooks
// ============================================================================

/**
 * Hook: Fetch active session plan for a player
 *
 * @param playerId - The player ID to fetch the session for
 * @param initialData - Optional initial data from server-side props (avoids loading state on direct page load)
 */
export function useActiveSessionPlan(playerId: string | null, initialData?: SessionPlan | null) {
  return useQuery({
    queryKey: sessionPlanKeys.active(playerId ?? ''),
    queryFn: () => fetchActiveSessionPlan(playerId!),
    enabled: !!playerId,
    // Use server-provided data as initial cache value
    // This prevents a loading flash on direct page loads while still allowing refetch
    initialData: initialData ?? undefined,
    // Don't refetch on mount if we have initial data - trust the server
    // The query will still refetch on window focus or after stale time
    staleTime: initialData ? 30000 : 0, // 30s stale time if we have initial data
  })
}

/**
 * Hook: Fetch active session plan with Suspense (for SSR contexts)
 */
export function useActiveSessionPlanSuspense(playerId: string) {
  return useSuspenseQuery({
    queryKey: sessionPlanKeys.active(playerId),
    queryFn: () => fetchActiveSessionPlan(playerId),
  })
}

/** Output from the session-plan background task */
interface SessionPlanTaskOutput {
  plan: SessionPlan
}

/**
 * Hook: Generate a new session plan via background task
 *
 * Returns a mutation to start generation plus real-time progress tracking.
 * The mutation resolves with the task ID; the plan is delivered via Socket.IO.
 */
export function useGenerateSessionPlan() {
  const queryClient = useQueryClient()
  const [taskId, setTaskId] = useState<string | null>(null)
  const task = useBackgroundTask<SessionPlanTaskOutput>(taskId)

  // Track the playerId for cache updates when task completes
  const playerIdRef = useRef<string | null>(null)
  // Track whether we've already processed this task completion
  const processedTaskIdRef = useRef<string | null>(null)

  // When task completes, extract plan and update React Query cache
  useEffect(() => {
    if (
      task.state?.status === 'completed' &&
      task.state.output?.plan &&
      taskId &&
      processedTaskIdRef.current !== taskId
    ) {
      processedTaskIdRef.current = taskId
      const plan = task.state.output.plan
      const playerId = playerIdRef.current
      if (playerId) {
        queryClient.setQueryData(sessionPlanKeys.active(playerId), plan)
        queryClient.setQueryData(sessionPlanKeys.detail(plan.id), plan)
      }
    }
  }, [task.state?.status, task.state?.output, taskId, queryClient])

  const mutation = useMutation({
    mutationFn: async (params: GenerateSessionPlanParams) => {
      playerIdRef.current = params.playerId
      processedTaskIdRef.current = null
      const id = await createSessionPlanTask(params)
      setTaskId(id)
      return id
    },
    onError: (err) => {
      console.error('Failed to generate session plan:', err.message)
    },
  })

  const reset = useCallback(() => {
    mutation.reset()
    setTaskId(null)
    processedTaskIdRef.current = null
  }, [mutation])

  return {
    ...mutation,
    reset,
    taskId,
    taskState: task.state,
    progress: task.state?.progress ?? 0,
    progressMessage: task.state?.progressMessage ?? null,
    /** The generated plan, available when task completes */
    plan: task.state?.status === 'completed' ? (task.state.output?.plan ?? null) : null,
    /** Whether the background task is actively running */
    isGenerating: mutation.isPending || (!!taskId && task.state?.status === 'running'),
    /** Whether the plan generation is complete */
    isComplete: task.state?.status === 'completed',
    /** Error from the background task (if it failed) */
    taskError: task.state?.status === 'failed' ? task.state.error : null,
  }
}

/**
 * Hook: Approve a session plan (teacher clicks "Let's Go!")
 */
export function useApproveSessionPlan() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({ playerId, planId }: { playerId: string; planId: string }) =>
      updateSessionPlan({ playerId, planId, action: 'approve' }),
    onSuccess: (plan, { playerId }) => {
      queryClient.setQueryData(sessionPlanKeys.active(playerId), plan)
      queryClient.setQueryData(sessionPlanKeys.detail(plan.id), plan)
    },
    onError: (err) => {
      console.error('Failed to approve session plan:', err.message)
    },
  })
}

/**
 * Hook: Start a session plan (begin practice)
 */
export function useStartSessionPlan() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({ playerId, planId }: { playerId: string; planId: string }) =>
      updateSessionPlan({ playerId, planId, action: 'start' }),
    onSuccess: (plan, { playerId }) => {
      queryClient.setQueryData(sessionPlanKeys.active(playerId), plan)
      queryClient.setQueryData(sessionPlanKeys.detail(plan.id), plan)
    },
    onError: (err) => {
      console.error('Failed to start session plan:', err.message)
    },
  })
}

/**
 * Hook: Record a slot result (answer submitted)
 */
export function useRecordSlotResult() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({
      playerId,
      planId,
      result,
    }: {
      playerId: string
      planId: string
      result: Omit<SlotResult, 'timestamp' | 'partNumber'>
    }) => updateSessionPlan({ playerId, planId, action: 'record', result }),
    onSuccess: (plan, { playerId }) => {
      queryClient.setQueryData(sessionPlanKeys.active(playerId), plan)
      queryClient.setQueryData(sessionPlanKeys.detail(plan.id), plan)
    },
    onError: (err) => {
      console.error('Failed to record slot result:', err.message)
    },
  })
}

/**
 * Hook: End session early
 */
export function useEndSessionEarly() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({
      playerId,
      planId,
      reason,
    }: {
      playerId: string
      planId: string
      reason?: string
    }) => updateSessionPlan({ playerId, planId, action: 'end_early', reason }),
    onSuccess: (plan, { playerId }) => {
      queryClient.setQueryData(sessionPlanKeys.active(playerId), plan)
      queryClient.setQueryData(sessionPlanKeys.detail(plan.id), plan)
      // Invalidate the list to show in history
      queryClient.invalidateQueries({ queryKey: sessionPlanKeys.lists() })
    },
    onError: (err) => {
      console.error('Failed to end session early:', err.message)
    },
  })
}

/**
 * Hook: Mark part transition complete and advance flow state.
 */
export function useCompletePartTransition() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({
      playerId,
      planId,
      expectedFlowVersion,
      shouldRunBreak,
    }: {
      playerId: string
      planId: string
      expectedFlowVersion?: number
      shouldRunBreak: boolean
    }) =>
      applySessionFlowEvent({
        playerId,
        planId,
        expectedFlowVersion,
        event: { type: 'PART_TRANSITION_COMPLETED', shouldRunBreak },
      }),
    onSuccess: (plan, { playerId }) => {
      queryClient.setQueryData(sessionPlanKeys.active(playerId), plan)
      queryClient.setQueryData(sessionPlanKeys.detail(plan.id), plan)
    },
    onError: (err) => {
      console.error('Failed to complete part transition:', err.message)
    },
  })
}

/**
 * Hook: Persist game break completion and advance flow state.
 */
export function useFinishGameBreak() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({
      playerId,
      planId,
      breakFinishReason,
      breakResults,
      expectedFlowVersion,
    }: {
      playerId: string
      planId: string
      breakFinishReason: 'timeout' | 'gameFinished' | 'skipped'
      breakResults?: GameResultsReport | null
      expectedFlowVersion?: number
    }) =>
      applySessionFlowEvent({
        playerId,
        planId,
        expectedFlowVersion,
        event: {
          type: 'BREAK_FINISHED',
          reason: breakFinishReason,
          results: breakResults ?? null,
        },
      }),
    onSuccess: (plan, { playerId }) => {
      queryClient.setQueryData(sessionPlanKeys.active(playerId), plan)
      queryClient.setQueryData(sessionPlanKeys.detail(plan.id), plan)
    },
    onError: (err) => {
      console.error('Failed to finish game break:', err.message)
    },
  })
}

/**
 * Hook: Mark game break as started and persist selected game.
 */
export function useStartGameBreak() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({
      playerId,
      planId,
      game,
      expectedFlowVersion,
    }: {
      playerId: string
      planId: string
      game?: string | null
      expectedFlowVersion?: number
    }) =>
      applySessionFlowEvent({
        playerId,
        planId,
        expectedFlowVersion,
        event: { type: 'BREAK_STARTED', game },
      }),
    onSuccess: (plan, { playerId }) => {
      queryClient.setQueryData(sessionPlanKeys.active(playerId), plan)
      queryClient.setQueryData(sessionPlanKeys.detail(plan.id), plan)
    },
    onError: (err) => {
      console.error('Failed to start game break:', err.message)
    },
  })
}

/**
 * Hook: Acknowledge game break results screen and return to practicing.
 */
export function useAcknowledgeGameBreakResults() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({
      playerId,
      planId,
      expectedFlowVersion,
    }: {
      playerId: string
      planId: string
      expectedFlowVersion?: number
    }) =>
      applySessionFlowEvent({
        playerId,
        planId,
        expectedFlowVersion,
        event: { type: 'BREAK_RESULTS_ACKED' },
      }),
    onSuccess: (plan, { playerId }) => {
      queryClient.setQueryData(sessionPlanKeys.active(playerId), plan)
      queryClient.setQueryData(sessionPlanKeys.detail(plan.id), plan)
    },
    onError: (err) => {
      console.error('Failed to acknowledge game break results:', err.message)
    },
  })
}

/**
 * Hook: Abandon session (user navigates away)
 */
export function useAbandonSession() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({ playerId, planId }: { playerId: string; planId: string }) =>
      updateSessionPlan({ playerId, planId, action: 'abandon' }),
    onSuccess: (plan, { playerId }) => {
      queryClient.setQueryData(sessionPlanKeys.active(playerId), null)
      queryClient.setQueryData(sessionPlanKeys.detail(plan.id), plan)
      queryClient.invalidateQueries({ queryKey: sessionPlanKeys.lists() })
    },
    onError: (err) => {
      console.error('Failed to abandon session:', err.message)
    },
  })
}

/**
 * Hook: Record a redo result (student re-attempts a previously completed problem)
 *
 * This is different from useRecordSlotResult because:
 * - It doesn't advance the session position (student returns to where they were)
 * - It can "redeem" incorrect answers (remove from retry queue if original was wrong and redo is correct)
 * - If original was correct and redo is wrong, no result is recorded (avoid penalty)
 */
export function useRecordRedoResult() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({
      playerId,
      planId,
      result,
      redoContext,
    }: {
      playerId: string
      planId: string
      result: Omit<SlotResult, 'timestamp' | 'partNumber'>
      redoContext: RedoContext
    }) => recordRedoResult({ playerId, planId, result, redoContext }),
    onSuccess: (plan, { playerId }) => {
      queryClient.setQueryData(sessionPlanKeys.active(playerId), plan)
      queryClient.setQueryData(sessionPlanKeys.detail(plan.id), plan)
    },
    onError: (err) => {
      console.error('Failed to record redo result:', err.message)
    },
  })
}

/**
 * Update the remote camera session ID for a session plan
 */
async function setRemoteCameraSession({
  playerId,
  planId,
  remoteCameraSessionId,
}: {
  playerId: string
  planId: string
  remoteCameraSessionId: string | null
}): Promise<SessionPlan> {
  const res = await api(`curriculum/${playerId}/sessions/plans/${planId}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      action: 'set_remote_camera',
      remoteCameraSessionId,
    }),
  })
  if (!res.ok) {
    const error = await res.json().catch(() => ({}))
    throw new Error(error.error || 'Failed to set remote camera session')
  }
  const data = await res.json()
  return data.plan
}

/**
 * Hook: Set the remote camera session ID for a session plan
 * Used when setting up phone camera for vision-based practice
 */
export function useSetRemoteCameraSession() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: setRemoteCameraSession,
    onSuccess: (plan, { playerId }) => {
      queryClient.setQueryData(sessionPlanKeys.active(playerId), plan)
      queryClient.setQueryData(sessionPlanKeys.detail(plan.id), plan)
    },
    onError: (err) => {
      console.error('Failed to set remote camera session:', err.message)
    },
  })
}