All files / web/src/arcade-games/card-sorting Validator.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import type {
  GameValidator,
  PracticeBreakOptions,
  ValidationContext,
  ValidationResult,
} from '@/lib/arcade/validation/types'
import {
  CardSortingStateSchema,
  type CardSortingConfig,
  type CardSortingMove,
  type CardSortingState,
  type CardPosition,
  type SortingCard,
} from './types'
import { calculateScore } from './utils/scoringAlgorithm'
import { placeCardAtPosition, insertCardAtPosition, removeCardAtPosition } from './utils/validation'

// Default config for practice breaks (quick games)
const PRACTICE_BREAK_DEFAULTS: CardSortingConfig = {
  cardCount: 5,
  timeLimit: null,
  gameMode: 'solo',
}

/**
 * Generate random sorting cards for practice break mode.
 * Creates minimal cards with placeholder SVG - client will render AbacusReact.
 */
function generatePracticeBreakCards(count: number): SortingCard[] {
  // Generate unique random numbers
  const numbers = new Set<number>()
  while (numbers.size < count) {
    const num = Math.floor(Math.random() * 100) // 0-99
    numbers.add(num)
  }

  // Create card objects in random order
  const shuffledNumbers = Array.from(numbers).sort(() => Math.random() - 0.5)

  return shuffledNumbers.map((number, index) => ({
    id: `practice-card-${index}-${number}`,
    number,
    // Placeholder SVG - client will render actual AbacusReact
    svgContent: `<svg viewBox="0 0 100 100"><text x="50" y="50" text-anchor="middle">${number}</text></svg>`,
  }))
}

export class CardSortingValidator implements GameValidator<CardSortingState, CardSortingMove> {
  // Zod schema for runtime validation of state loaded from database
  stateSchema = CardSortingStateSchema

  validateMove(
    state: CardSortingState,
    move: CardSortingMove,
    context: ValidationContext
  ): ValidationResult {
    switch (move.type) {
      case 'START_GAME':
        return this.validateStartGame(state, move.data, move.playerId)
      case 'PLACE_CARD':
        return this.validatePlaceCard(state, move.data.cardId, move.data.position)
      case 'INSERT_CARD':
        return this.validateInsertCard(state, move.data.cardId, move.data.insertPosition)
      case 'REMOVE_CARD':
        return this.validateRemoveCard(state, move.data.position)
      case 'CHECK_SOLUTION':
        return this.validateCheckSolution(state, move.data.finalSequence)
      case 'GO_TO_SETUP':
        return this.validateGoToSetup(state)
      case 'SET_CONFIG':
        return this.validateSetConfig(state, move.data.field, move.data.value)
      case 'RESUME_GAME':
        return this.validateResumeGame(state)
      case 'UPDATE_CARD_POSITIONS':
        return this.validateUpdateCardPositions(state, move.data.positions)
      default:
        return {
          valid: false,
          error: `Unknown move type: ${(move as CardSortingMove).type}`,
        }
    }
  }

  private validateStartGame(
    state: CardSortingState,
    data: { playerMetadata: unknown; selectedCards: unknown },
    playerId: string
  ): ValidationResult {
    // Allow starting a new game from any phase (for "Play Again" button)

    // Validate selectedCards
    if (!Array.isArray(data.selectedCards)) {
      return { valid: false, error: 'selectedCards must be an array' }
    }

    if (data.selectedCards.length !== state.cardCount) {
      return {
        valid: false,
        error: `Must provide exactly ${state.cardCount} cards`,
      }
    }

    const selectedCards = data.selectedCards as unknown[]

    // Create correct order (sorted)
    const correctOrder = [...selectedCards].sort((a: unknown, b: unknown) => {
      const cardA = a as { number: number }
      const cardB = b as { number: number }
      return cardA.number - cardB.number
    })

    return {
      valid: true,
      newState: {
        ...state,
        gamePhase: 'playing',
        playerId,
        playerMetadata: data.playerMetadata,
        gameStartTime: Date.now(),
        gameEndTime: null,
        selectedCards: selectedCards as typeof state.selectedCards,
        correctOrder: correctOrder as typeof state.correctOrder,
        availableCards: selectedCards as typeof state.availableCards,
        placedCards: new Array(state.cardCount).fill(null),
        cardPositions: [], // Will be set by first position update
        scoreBreakdown: null,
      },
    }
  }

  private validatePlaceCard(
    state: CardSortingState,
    cardId: string,
    position: number
  ): ValidationResult {
    // Must be in playing phase
    if (state.gamePhase !== 'playing') {
      return {
        valid: false,
        error: 'Can only place cards during playing phase',
      }
    }

    // Card must exist in availableCards
    const card = state.availableCards.find((c) => c.id === cardId)
    if (!card) {
      return { valid: false, error: 'Card not found in available cards' }
    }

    // Position must be valid (0 to cardCount-1)
    if (position < 0 || position >= state.cardCount) {
      return {
        valid: false,
        error: `Invalid position: must be between 0 and ${state.cardCount - 1}`,
      }
    }

    // Place the card using utility function (simple replacement)
    const { placedCards: newPlaced, replacedCard } = placeCardAtPosition(
      state.placedCards,
      card,
      position
    )

    // Remove card from available
    let newAvailable = state.availableCards.filter((c) => c.id !== cardId)

    // If slot was occupied, add replaced card back to available
    if (replacedCard) {
      newAvailable = [...newAvailable, replacedCard]
    }

    return {
      valid: true,
      newState: {
        ...state,
        availableCards: newAvailable,
        placedCards: newPlaced,
      },
    }
  }

  private validateInsertCard(
    state: CardSortingState,
    cardId: string,
    insertPosition: number
  ): ValidationResult {
    // Must be in playing phase
    if (state.gamePhase !== 'playing') {
      return {
        valid: false,
        error: 'Can only insert cards during playing phase',
      }
    }

    // Card must exist in availableCards
    const card = state.availableCards.find((c) => c.id === cardId)
    if (!card) {
      return { valid: false, error: 'Card not found in available cards' }
    }

    // Position must be valid (0 to cardCount, inclusive - can insert after last position)
    if (insertPosition < 0 || insertPosition > state.cardCount) {
      return {
        valid: false,
        error: `Invalid insert position: must be between 0 and ${state.cardCount}`,
      }
    }

    // Insert the card using utility function (with shift and compact)
    const { placedCards: newPlaced, excessCards } = insertCardAtPosition(
      state.placedCards,
      card,
      insertPosition,
      state.cardCount
    )

    // Remove card from available
    let newAvailable = state.availableCards.filter((c) => c.id !== cardId)

    // Add any excess cards back to available (shouldn't normally happen)
    if (excessCards.length > 0) {
      newAvailable = [...newAvailable, ...excessCards]
    }

    return {
      valid: true,
      newState: {
        ...state,
        availableCards: newAvailable,
        placedCards: newPlaced,
      },
    }
  }

  private validateRemoveCard(state: CardSortingState, position: number): ValidationResult {
    // Must be in playing phase
    if (state.gamePhase !== 'playing') {
      return {
        valid: false,
        error: 'Can only remove cards during playing phase',
      }
    }

    // Position must be valid
    if (position < 0 || position >= state.cardCount) {
      return {
        valid: false,
        error: `Invalid position: must be between 0 and ${state.cardCount - 1}`,
      }
    }

    // Card must exist at position
    if (state.placedCards[position] === null) {
      return { valid: false, error: 'No card at this position' }
    }

    // Remove the card using utility function
    const { placedCards: newPlaced, removedCard } = removeCardAtPosition(
      state.placedCards,
      position
    )

    if (!removedCard) {
      return { valid: false, error: 'Failed to remove card' }
    }

    // Add back to available
    const newAvailable = [...state.availableCards, removedCard]

    return {
      valid: true,
      newState: {
        ...state,
        availableCards: newAvailable,
        placedCards: newPlaced,
      },
    }
  }

  private validateCheckSolution(
    state: CardSortingState,
    finalSequence?: typeof state.selectedCards
  ): ValidationResult {
    // Must be in playing phase
    if (state.gamePhase !== 'playing') {
      return {
        valid: false,
        error: 'Can only check solution during playing phase',
      }
    }

    // Use finalSequence if provided, otherwise use placedCards
    const userCards =
      finalSequence ||
      state.placedCards.filter((c): c is (typeof state.selectedCards)[0] => c !== null)

    // Must have all cards
    if (userCards.length !== state.cardCount) {
      return { valid: false, error: 'Must place all cards before checking' }
    }

    // Calculate score using scoring algorithms
    const userSequence = userCards.map((c) => c.number)
    const correctSequence = state.correctOrder.map((c) => c.number)

    const scoreBreakdown = calculateScore(
      userSequence,
      correctSequence,
      state.gameStartTime || Date.now()
    )

    // If finalSequence was provided, update placedCards with it
    const newPlacedCards = finalSequence
      ? [...userCards, ...new Array(state.cardCount - userCards.length).fill(null)]
      : state.placedCards

    return {
      valid: true,
      newState: {
        ...state,
        gamePhase: 'results',
        gameEndTime: Date.now(),
        scoreBreakdown,
        placedCards: newPlacedCards,
        availableCards: [], // All cards are now placed
      },
    }
  }

  private validateGoToSetup(state: CardSortingState): ValidationResult {
    // Save current game state for resume (if in playing phase)
    if (state.gamePhase === 'playing') {
      return {
        valid: true,
        newState: {
          ...this.getInitialState({
            cardCount: state.cardCount,
            timeLimit: state.timeLimit,
            gameMode: state.gameMode,
          }),
          originalConfig: {
            cardCount: state.cardCount,
            timeLimit: state.timeLimit,
            gameMode: state.gameMode,
          },
          pausedGamePhase: 'playing',
          pausedGameState: {
            selectedCards: state.selectedCards,
            availableCards: state.availableCards,
            placedCards: state.placedCards,
            cardPositions: state.cardPositions,
            gameStartTime: state.gameStartTime || Date.now(),
          },
        },
      }
    }

    // Just go to setup
    return {
      valid: true,
      newState: this.getInitialState({
        cardCount: state.cardCount,
        timeLimit: state.timeLimit,
        gameMode: state.gameMode,
      }),
    }
  }

  private validateSetConfig(
    state: CardSortingState,
    field: string,
    value: unknown
  ): ValidationResult {
    // Must be in setup phase
    if (state.gamePhase !== 'setup') {
      return { valid: false, error: 'Can only change config in setup phase' }
    }

    // Validate field and value
    switch (field) {
      case 'cardCount':
        if (![5, 8, 12, 15].includes(value as number)) {
          return { valid: false, error: 'cardCount must be 5, 8, 12, or 15' }
        }
        return {
          valid: true,
          newState: {
            ...state,
            cardCount: value as 5 | 8 | 12 | 15,
            placedCards: new Array(value as number).fill(null),
            // Clear pause state if config changed
            pausedGamePhase: undefined,
            pausedGameState: undefined,
          },
        }

      case 'timeLimit':
        if (value !== null && (typeof value !== 'number' || value < 30)) {
          return {
            valid: false,
            error: 'timeLimit must be null or a number >= 30',
          }
        }
        return {
          valid: true,
          newState: {
            ...state,
            timeLimit: value as number | null,
            // Clear pause state if config changed
            pausedGamePhase: undefined,
            pausedGameState: undefined,
          },
        }

      case 'gameMode':
        if (!['solo', 'collaborative', 'competitive', 'relay'].includes(value as string)) {
          return {
            valid: false,
            error: 'gameMode must be solo, collaborative, competitive, or relay',
          }
        }
        return {
          valid: true,
          newState: {
            ...state,
            gameMode: value as 'solo' | 'collaborative' | 'competitive' | 'relay',
            // Clear pause state if config changed
            pausedGamePhase: undefined,
            pausedGameState: undefined,
          },
        }

      default:
        return { valid: false, error: `Unknown config field: ${field}` }
    }
  }

  private validateResumeGame(state: CardSortingState): ValidationResult {
    // Must be in setup phase
    if (state.gamePhase !== 'setup') {
      return { valid: false, error: 'Can only resume from setup phase' }
    }

    // Must have paused game state
    if (!state.pausedGamePhase || !state.pausedGameState) {
      return { valid: false, error: 'No paused game to resume' }
    }

    // Restore paused state
    return {
      valid: true,
      newState: {
        ...state,
        gamePhase: state.pausedGamePhase,
        selectedCards: state.pausedGameState.selectedCards,
        correctOrder: [...state.pausedGameState.selectedCards].sort((a, b) => a.number - b.number),
        availableCards: state.pausedGameState.availableCards,
        placedCards: state.pausedGameState.placedCards,
        cardPositions: state.pausedGameState.cardPositions,
        gameStartTime: state.pausedGameState.gameStartTime,
        pausedGamePhase: undefined,
        pausedGameState: undefined,
      },
    }
  }

  private validateUpdateCardPositions(
    state: CardSortingState,
    positions: CardPosition[]
  ): ValidationResult {
    // Must be in playing phase
    if (state.gamePhase !== 'playing') {
      return {
        valid: false,
        error: 'Can only update positions during playing phase',
      }
    }

    // Validate positions array
    if (!Array.isArray(positions)) {
      return { valid: false, error: 'positions must be an array' }
    }

    // Basic validation of position values
    for (const pos of positions) {
      if (typeof pos.x !== 'number' || pos.x < 0 || pos.x > 100) {
        return { valid: false, error: 'x must be between 0 and 100' }
      }
      if (typeof pos.y !== 'number' || pos.y < 0 || pos.y > 100) {
        return { valid: false, error: 'y must be between 0 and 100' }
      }
      if (typeof pos.rotation !== 'number') {
        return { valid: false, error: 'rotation must be a number' }
      }
      if (typeof pos.zIndex !== 'number') {
        return { valid: false, error: 'zIndex must be a number' }
      }
      if (typeof pos.cardId !== 'string') {
        return { valid: false, error: 'cardId must be a string' }
      }
    }

    return {
      valid: true,
      newState: {
        ...state,
        cardPositions: positions,
      },
    }
  }

  isGameComplete(state: CardSortingState): boolean {
    return state.gamePhase === 'results'
  }

  /**
   * Get initial state for practice break mode.
   * Skips setup phase and starts directly in 'playing' phase with generated cards.
   *
   * @param config Partial config to merge with practice break defaults
   * @param options Practice break options including player info
   * @returns Game state ready to play immediately
   */
  getInitialStateForPracticeBreak(
    config: Partial<CardSortingConfig>,
    options: PracticeBreakOptions
  ): CardSortingState {
    // Merge with practice break defaults
    const fullConfig: CardSortingConfig = {
      ...PRACTICE_BREAK_DEFAULTS,
      ...config,
    }

    // Adjust card count based on break duration
    if (options.maxDurationMinutes <= 2 && fullConfig.cardCount > 5) {
      fullConfig.cardCount = 5
    } else if (options.maxDurationMinutes <= 4 && fullConfig.cardCount > 8) {
      fullConfig.cardCount = 8
    }

    // Generate cards for the game
    const selectedCards = generatePracticeBreakCards(fullConfig.cardCount)

    // Create correct order (sorted by number)
    const correctOrder = [...selectedCards].sort((a, b) => a.number - b.number)

    // Set up single player
    const playerId = options.playerId
    const playerMetadata = {
      id: playerId,
      name: options.playerName || 'Player',
      emoji: '🎮',
      userId: playerId,
    }

    return {
      cardCount: fullConfig.cardCount,
      timeLimit: fullConfig.timeLimit,
      gameMode: fullConfig.gameMode,
      // Start in playing phase - skip setup!
      gamePhase: 'playing',
      playerId,
      playerMetadata,
      activePlayers: [playerId],
      allPlayerMetadata: { [playerId]: playerMetadata },
      gameStartTime: Date.now(),
      gameEndTime: null,
      selectedCards,
      correctOrder,
      availableCards: selectedCards, // Cards start in available pool
      placedCards: new Array(fullConfig.cardCount).fill(null),
      cardPositions: [],
      cursorPositions: {},
      selectedCardId: null,
      scoreBreakdown: null,
    }
  }

  getInitialState(config: CardSortingConfig): CardSortingState {
    return {
      cardCount: config.cardCount,
      timeLimit: config.timeLimit,
      gameMode: config.gameMode,
      gamePhase: 'setup',
      playerId: '',
      playerMetadata: {
        id: '',
        name: '',
        emoji: '',
        userId: '',
      },
      activePlayers: [],
      allPlayerMetadata: {},
      gameStartTime: null,
      gameEndTime: null,
      selectedCards: [],
      correctOrder: [],
      availableCards: [],
      placedCards: new Array(config.cardCount).fill(null),
      cardPositions: [],
      cursorPositions: {},
      selectedCardId: null,
      scoreBreakdown: null,
    }
  }
}

export const cardSortingValidator = new CardSortingValidator()