All files / web/src/lib/curriculum progress-manager.ts

40.74% Statements 447/1097
78.12% Branches 25/32
6.66% Functions 2/30
40.74% Lines 447/1097

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 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 10982x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x             2x 2x 2x 2x                                                               2x 2x 2x 2x                     2x 2x 2x 2x 2x 2x 2x 2x                         2x 2x 2x 2x             2x 2x 2x 2x                   2x 2x 2x 2x 2x 2x 2x 2x                                                                                         2x 2x 2x 2x 2x 2x 2x                                         2x 2x 2x 2x             2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                                                                                                                       2x 2x 2x 2x 2x 2x 2x 2x 2x                                                                   2x 2x 2x 2x 2x 2x 2x 2x 2x                                                                           2x 2x 2x 2x 2x                                           2x 2x 2x 2x                           2x 2x 2x 2x                           2x 2x 2x 2x             2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 11x 11x 11x         11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 8x 8x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 3x 3x 3x 3x 3x 3x 3x 3x 3x 12x 12x 12x 12x 12x 12x 12x 12x 12x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 101x 101x         101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 101x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                                                             2x 2x 2x 2x 2x               2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                                                                                                                                                                                     2x 2x 2x 2x 2x                                         2x 2x 2x 2x 2x 2x 2x 2x                         2x 2x 2x 2x           2x 2x 2x 2x 2x               2x 2x 2x 2x                                                                   2x 2x 2x 2x 2x                                                                         2x 2x 2x 2x 2x                                                                   2x 2x 2x 2x 2x                   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                                                                      
/**
 * Progress manager for curriculum tracking
 * Handles CRUD operations for student curriculum progress and skill mastery
 */
 
import { and, desc, eq, inArray, lt, ne, or } from 'drizzle-orm'
import { db, schema } from '@/db'
import type { NewPlayerCurriculum, PlayerCurriculum } from '@/db/schema/player-curriculum'
import type { NewPlayerSkillMastery, PlayerSkillMastery } from '@/db/schema/player-skill-mastery'
import { type PracticeLevel, isActive } from '@/db/schema/player-skill-mastery'
import type { PracticeSession } from '@/db/schema/practice-sessions'
import {
  isTutorialSatisfied,
  type NewSkillTutorialProgress,
  type SkillTutorialProgress,
} from '@/db/schema/skill-tutorial-progress'
import { getRecentSessionResults } from '@/lib/curriculum/session-planner'
 
// ============================================================================
// CURRICULUM POSITION OPERATIONS
// ============================================================================
 
/**
 * Get a player's curriculum position
 * Returns null if the player hasn't started the curriculum
 */
export async function getPlayerCurriculum(playerId: string): Promise<PlayerCurriculum | null> {
  const result = await db.query.playerCurriculum.findFirst({
    where: eq(schema.playerCurriculum.playerId, playerId),
  })
  return result ?? null
}
 
/**
 * Create or update a player's curriculum position
 */
export async function upsertPlayerCurriculum(
  playerId: string,
  data: Partial<Omit<NewPlayerCurriculum, 'playerId'>>
): Promise<PlayerCurriculum> {
  const existing = await getPlayerCurriculum(playerId)

  if (existing) {
    // Update existing record
    await db
      .update(schema.playerCurriculum)
      .set({
        ...data,
        updatedAt: new Date(),
      })
      .where(eq(schema.playerCurriculum.playerId, playerId))

    return (await getPlayerCurriculum(playerId))!
  }

  // Create new record with defaults
  const newRecord: NewPlayerCurriculum = {
    playerId,
    currentLevel: data.currentLevel ?? 1,
    currentPhaseId: data.currentPhaseId ?? 'L1.add.+1.direct',
    worksheetPreset: data.worksheetPreset ?? null,
    visualizationMode: data.visualizationMode ?? false,
  }

  await db.insert(schema.playerCurriculum).values(newRecord)
  return (await getPlayerCurriculum(playerId))!
}
 
/**
 * Advance a player to the next curriculum phase
 */
export async function advanceToNextPhase(
  playerId: string,
  nextPhaseId: string,
  nextLevel?: number
): Promise<PlayerCurriculum> {
  return upsertPlayerCurriculum(playerId, {
    currentPhaseId: nextPhaseId,
    ...(nextLevel !== undefined ? { currentLevel: nextLevel } : {}),
  })
}
 
// ============================================================================
// SKILL MASTERY OPERATIONS
// ============================================================================
 
/**
 * Get a player's mastery for a specific skill
 */
export async function getSkillMastery(
  playerId: string,
  skillId: string
): Promise<PlayerSkillMastery | null> {
  const result = await db.query.playerSkillMastery.findFirst({
    where: and(
      eq(schema.playerSkillMastery.playerId, playerId),
      eq(schema.playerSkillMastery.skillId, skillId)
    ),
  })
  return result ?? null
}
 
/**
 * Get all skill mastery records for a player
 */
export async function getAllSkillMastery(playerId: string): Promise<PlayerSkillMastery[]> {
  return db.query.playerSkillMastery.findMany({
    where: eq(schema.playerSkillMastery.playerId, playerId),
    orderBy: desc(schema.playerSkillMastery.lastPracticedAt),
  })
}
 
/**
 * Get all skills in a player's active practice rotation (practiceLevel != 'none')
 */
export async function getPracticingSkills(playerId: string): Promise<PlayerSkillMastery[]> {
  return db.query.playerSkillMastery.findMany({
    where: and(
      eq(schema.playerSkillMastery.playerId, playerId),
      ne(schema.playerSkillMastery.practiceLevel, 'none')
    ),
    orderBy: desc(schema.playerSkillMastery.lastPracticedAt),
  })
}
 
/**
 * Set practice levels for a player's skills.
 *
 * @param playerId - The player to update
 * @param skillLevels - Map of skillId → PracticeLevel
 * @returns All skill mastery records for the player after update
 */
export async function setSkillPracticeLevels(
  playerId: string,
  skillLevels: Record<string, PracticeLevel>
): Promise<PlayerSkillMastery[]> {
  const now = new Date()

  // Get all existing skills for this player
  const existingSkills = await getAllSkillMastery(playerId)
  const existingSkillIds = new Set(existingSkills.map((s) => s.skillId))

  // Update existing skills
  for (const skill of existingSkills) {
    const newLevel = skillLevels[skill.skillId] ?? 'none'
    const isNowPracticing = isActive(newLevel)

    // Only update if something changed
    if (skill.practiceLevel !== newLevel || skill.isPracticing !== isNowPracticing) {
      await db
        .update(schema.playerSkillMastery)
        .set({
          practiceLevel: newLevel,
          isPracticing: isNowPracticing,
          updatedAt: now,
        })
        .where(eq(schema.playerSkillMastery.id, skill.id))
    }
  }

  // Create new skills that don't exist yet
  for (const [skillId, level] of Object.entries(skillLevels)) {
    if (!existingSkillIds.has(skillId) && isActive(level)) {
      const newRecord: NewPlayerSkillMastery = {
        playerId,
        skillId,
        isPracticing: true,
        practiceLevel: level,
        lastPracticedAt: now,
      }
      await db.insert(schema.playerSkillMastery).values(newRecord)
    }
  }

  return getAllSkillMastery(playerId)
}
 
/**
 * Set which skills are in a player's active practice rotation.
 * Backwards-compatible: treats all provided skills as 'visual' level.
 *
 * @deprecated Use setSkillPracticeLevels instead.
 */
export async function setPracticingSkills(
  playerId: string,
  practicingSkillIds: string[]
): Promise<PlayerSkillMastery[]> {
  // Get all existing skills to know which ones to set to 'none'
  const existingSkills = await getAllSkillMastery(playerId)
  const levels: Record<string, PracticeLevel> = {}

  // Set existing skills not in the list to 'none'
  for (const skill of existingSkills) {
    levels[skill.skillId] = 'none'
  }

  // Set all provided skills to 'visual' (preserves legacy behavior)
  for (const skillId of practicingSkillIds) {
    levels[skillId] = 'visual'
  }

  return setSkillPracticeLevels(playerId, levels)
}
 
/**
 * @deprecated Use setSkillPracticeLevels instead. Kept for backwards compatibility.
 */
export async function setMasteredSkills(
  playerId: string,
  masteredSkillIds: string[]
): Promise<PlayerSkillMastery[]> {
  return setPracticingSkills(playerId, masteredSkillIds)
}
 
/**
 * Refresh skill recency by inserting a sentinel record
 *
 * Use this when a teacher wants to mark a skill as "recently practiced"
 * (e.g., student did offline workbooks). This inserts a "recency-refresh"
 * sentinel record that BKT sees for lastPracticedAt but ignores for pKnown.
 *
 * The sentinel approach means:
 * - Single source of truth: all lastPracticedAt comes from problem history
 * - No abstraction gap: BKT naturally handles recency from the same data source
 * - Clear semantics: sentinel records are clearly marked with source='recency-refresh'
 *
 * @param playerId - The player's ID
 * @param skillId - The skill to refresh
 * @returns The created session plan containing the sentinel, or null if skill not found
 */
export async function refreshSkillRecency(
  playerId: string,
  skillId: string
): Promise<{ sessionId: string; timestamp: Date } | null> {
  const existing = await getSkillMastery(playerId, skillId)

  if (!existing) {
    return null
  }

  const now = new Date()

  // Create a minimal session plan with status='recency-refresh'
  // This contains a single sentinel SlotResult
  const sentinelResult: schema.SlotResult = {
    slotId: crypto.randomUUID(),
    partNumber: 1,
    slotIndex: 0,
    problem: {
      terms: [0],
      answer: 0,
      skillsRequired: [skillId],
    },
    studentAnswer: 0,
    isCorrect: true, // Doesn't matter - BKT ignores for recency-refresh
    responseTimeMs: 0,
    skillsExercised: [skillId],
    usedOnScreenAbacus: false,
    timestamp: now,
    hadHelp: false,
    incorrectAttempts: 0,
    source: 'recency-refresh', // This marks it as a sentinel record
  }

  const sessionPlan: schema.NewSessionPlan = {
    playerId,
    targetDurationMinutes: 0,
    estimatedProblemCount: 0,
    avgTimePerProblemSeconds: 0,
    parts: [], // No actual parts - just the sentinel result
    summary: {
      focusDescription: 'Recency refresh',
      totalProblemCount: 0,
      estimatedMinutes: 0,
      parts: [],
    },
    status: 'recency-refresh',
    results: [sentinelResult],
    createdAt: now,
    completedAt: now,
  }

  const [inserted] = await db.insert(schema.sessionPlans).values(sessionPlan).returning()

  return {
    sessionId: inserted.id,
    timestamp: now,
  }
}
 
/**
 * Record a skill attempt (correct or incorrect)
 * Updates the lastPracticedAt timestamp on the skill mastery record.
 *
 * NOTE: Attempt/correct statistics are now computed on-the-fly from session results.
 * This function only updates metadata fields (lastPracticedAt) and ensures the
 * skill record exists.
 */
export async function recordSkillAttempt(
  playerId: string,
  skillId: string,
  _isCorrect: boolean
): Promise<PlayerSkillMastery> {
  const existing = await getSkillMastery(playerId, skillId)
  const now = new Date()

  if (existing) {
    // Update lastPracticedAt timestamp
    await db
      .update(schema.playerSkillMastery)
      .set({
        lastPracticedAt: now,
        updatedAt: now,
      })
      .where(eq(schema.playerSkillMastery.id, existing.id))

    return (await getSkillMastery(playerId, skillId))!
  }

  // Create new record - if we're recording an attempt, this skill is being practiced
  const newRecord: NewPlayerSkillMastery = {
    playerId,
    skillId,
    isPracticing: true,
    practiceLevel: 'abacus',
    lastPracticedAt: now,
  }

  await db.insert(schema.playerSkillMastery).values(newRecord)
  return (await getSkillMastery(playerId, skillId))!
}
 
/**
 * Record a skill attempt with help tracking
 *
 * Updates the lastPracticedAt timestamp and tracks whether help was used.
 * BKT handles mastery estimation via evidence weighting (helped answers get 0.5x weight).
 *
 * NOTE: BKT's conjunctive blame attribution identifies weak skills from multi-skill problems.
 */
export async function recordSkillAttemptWithHelp(
  playerId: string,
  skillId: string,
  _isCorrect: boolean,
  hadHelp: boolean,
  _responseTimeMs?: number
): Promise<PlayerSkillMastery> {
  const existing = await getSkillMastery(playerId, skillId)
  const now = new Date()

  if (existing) {
    await db
      .update(schema.playerSkillMastery)
      .set({
        lastPracticedAt: now,
        updatedAt: now,
        lastHadHelp: hadHelp,
      })
      .where(eq(schema.playerSkillMastery.id, existing.id))

    return (await getSkillMastery(playerId, skillId))!
  }

  // Create new record with help tracking - skill is being practiced
  const newRecord: NewPlayerSkillMastery = {
    playerId,
    skillId,
    isPracticing: true,
    practiceLevel: 'abacus',
    lastPracticedAt: now,
    lastHadHelp: hadHelp,
  }

  await db.insert(schema.playerSkillMastery).values(newRecord)

  return (await getSkillMastery(playerId, skillId))!
}
 
/**
 * Record multiple skill attempts with help tracking (for batch updates after a problem)
 * Response time is shared across all skills since they come from the same problem
 */
export async function recordSkillAttemptsWithHelp(
  playerId: string,
  skillResults: Array<{ skillId: string; isCorrect: boolean }>,
  hadHelp: boolean,
  responseTimeMs?: number
): Promise<PlayerSkillMastery[]> {
  const results: PlayerSkillMastery[] = []

  for (const { skillId, isCorrect } of skillResults) {
    const result = await recordSkillAttemptWithHelp(
      playerId,
      skillId,
      isCorrect,
      hadHelp,
      responseTimeMs
    )
    results.push(result)
  }

  return results
}
 
/**
 * Record multiple skill attempts at once (for batch updates after a problem)
 */
export async function recordSkillAttempts(
  playerId: string,
  skillResults: Array<{ skillId: string; isCorrect: boolean }>
): Promise<PlayerSkillMastery[]> {
  const results: PlayerSkillMastery[] = []

  for (const { skillId, isCorrect } of skillResults) {
    const result = await recordSkillAttempt(playerId, skillId, isCorrect)
    results.push(result)
  }

  return results
}
 
/**
 * Calculate what percentage of given skills are being practiced
 */
export async function calculatePracticingPercent(
  playerId: string,
  skillIds: string[]
): Promise<number> {
  if (skillIds.length === 0) return 0

  const masteryRecords = await getAllSkillMastery(playerId)
  const relevantRecords = masteryRecords.filter((r) => skillIds.includes(r.skillId))

  const practicingCount = relevantRecords.filter((r) => isActive(r.practiceLevel)).length

  return Math.round((practicingCount / skillIds.length) * 100)
}
 
/**
 * @deprecated Use calculatePracticingPercent instead.
 */
export async function calculateMasteryPercent(
  playerId: string,
  skillIds: string[]
): Promise<number> {
  return calculatePracticingPercent(playerId, skillIds)
}
 
// ============================================================================
// PRACTICE SESSION OPERATIONS
// ============================================================================
 
/**
 * Get recent practice sessions for a player
 *
 * NOTE: This queries from session_plans (the active session system) and
 * transforms results into PracticeSession format for the dashboard.
 * The old practice_sessions table is no longer populated.
 */
export async function getRecentSessions(
  playerId: string,
  limit: number = 10
): Promise<PracticeSession[]> {
  // Query completed/abandoned sessions from session_plans.
  //
  // IMPORTANT: We explicitly project only the columns the transform below reads.
  // A previous version used `db.query.sessionPlans.findMany(...)` which selects
  // every column — including `parts` (10–50 KB of problem-generation traces per
  // row) — and blew libsql's response size cap on heavy users (issue #141).
  // Same pattern used by batchGetRecentSessionResults in session-planner.ts.
  const sessions = await db
    .select({
      id: schema.sessionPlans.id,
      playerId: schema.sessionPlans.playerId,
      results: schema.sessionPlans.results,
      startedAt: schema.sessionPlans.startedAt,
      createdAt: schema.sessionPlans.createdAt,
      completedAt: schema.sessionPlans.completedAt,
    })
    .from(schema.sessionPlans)
    .where(
      and(
        eq(schema.sessionPlans.playerId, playerId),
        inArray(schema.sessionPlans.status, ['completed', 'abandoned'])
      )
    )
    .orderBy(desc(schema.sessionPlans.completedAt))
    .limit(limit)
 
  // Transform session_plans data into PracticeSession format
  return sessions.map((session) => {
    // Parse results from JSON
    const results =
      (session.results as Array<{
        isCorrect: boolean
        responseTimeMs: number
        skillsExercised: string[]
      }>) || []
 
    const problemsAttempted = results.length
    const problemsCorrect = results.filter((r) => r.isCorrect).length
    const totalTimeMs = results.reduce((sum, r) => sum + (r.responseTimeMs || 0), 0)
    const averageTimeMs = problemsAttempted > 0 ? Math.round(totalTimeMs / problemsAttempted) : null
    const skillsUsed = [...new Set(results.flatMap((r) => r.skillsExercised || []))]
 
    return {
      id: session.id,
      playerId: session.playerId,
      phaseId: 'session', // session_plans don't have phaseId
      problemsAttempted,
      problemsCorrect,
      averageTimeMs,
      totalTimeMs,
      skillsUsed,
      visualizationMode: false, // Not tracked in session_plans
      startedAt: session.startedAt || session.createdAt,
      completedAt: session.completedAt,
    } as PracticeSession
  })
}
 
/**
 * Response type for paginated sessions
 */
export interface PaginatedSessionsResponse {
  sessions: PracticeSession[]
  nextCursor: string | null
  hasMore: boolean
}
 
/**
 * Get paginated sessions with cursor-based pagination
 * Cursor is the session ID to start after (for "load more" functionality)
 */
export async function getPaginatedSessions(
  playerId: string,
  limit: number = 20,
  cursor?: string
): Promise<PaginatedSessionsResponse> {
  console.log(`[getPaginatedSessions] playerId=${playerId}, limit=${limit}, cursor=${cursor}`)
 
  // If we have a cursor, we need to find sessions older than that cursor's completedAt.
  // Project only the two columns we read (id, completedAt) to avoid pulling
  // the heavy `parts`/`results` blobs just to check the cursor (#141).
  let cursorSession: { id: string; completedAt: Date | null } | null = null
  if (cursor) {
    cursorSession =
      (await db.query.sessionPlans.findFirst({
        where: eq(schema.sessionPlans.id, cursor),
        columns: { id: true, completedAt: true },
      })) ?? null
    console.log(
      `[getPaginatedSessions] cursorSession found: ${!!cursorSession}, completedAt=${cursorSession?.completedAt}`
    )
  }
 
  // Build the query conditions - include cursor condition in SQL for proper pagination
  const conditions = [
    eq(schema.sessionPlans.playerId, playerId),
    inArray(schema.sessionPlans.status, ['completed', 'abandoned']),
  ]
 
  // Add cursor condition to SQL query (sessions older than cursor)
  if (cursorSession?.completedAt) {
    // Sessions with earlier completedAt, OR same completedAt but smaller ID (for tie-breaking)
    conditions.push(
      or(
        lt(schema.sessionPlans.completedAt, cursorSession.completedAt),
        and(
          eq(schema.sessionPlans.completedAt, cursorSession.completedAt),
          lt(schema.sessionPlans.id, cursorSession.id)
        )
      )!
    )
  }
 
  // Query one extra to check if there are more.
  // Narrow projection — see getRecentSessions above for context (#141).
  const sessions = await db
    .select({
      id: schema.sessionPlans.id,
      playerId: schema.sessionPlans.playerId,
      results: schema.sessionPlans.results,
      startedAt: schema.sessionPlans.startedAt,
      createdAt: schema.sessionPlans.createdAt,
      completedAt: schema.sessionPlans.completedAt,
    })
    .from(schema.sessionPlans)
    .where(and(...conditions))
    .orderBy(desc(schema.sessionPlans.completedAt))
    .limit(limit + 1)
 
  console.log(`[getPaginatedSessions] Raw query returned ${sessions.length} sessions`)
 
  // Check if there are more results
  const hasMore = sessions.length > limit
  const resultSessions = hasMore ? sessions.slice(0, limit) : sessions
  console.log(`[getPaginatedSessions] Final: ${resultSessions.length} sessions, hasMore=${hasMore}`)
 
  // Transform to PracticeSession format
  const practiceSessionsResult = resultSessions.map((session) => {
    const results =
      (session.results as Array<{
        isCorrect: boolean
        responseTimeMs: number
        skillsExercised: string[]
      }>) || []
 
    const problemsAttempted = results.length
    const problemsCorrect = results.filter((r) => r.isCorrect).length
    const totalTimeMs = results.reduce((sum, r) => sum + (r.responseTimeMs || 0), 0)
    const averageTimeMs = problemsAttempted > 0 ? Math.round(totalTimeMs / problemsAttempted) : null
    const skillsUsed = [...new Set(results.flatMap((r) => r.skillsExercised || []))]
 
    return {
      id: session.id,
      playerId: session.playerId,
      phaseId: 'session',
      problemsAttempted,
      problemsCorrect,
      averageTimeMs,
      totalTimeMs,
      skillsUsed,
      visualizationMode: false,
      startedAt: session.startedAt || session.createdAt,
      completedAt: session.completedAt,
    } as PracticeSession
  })
 
  // Next cursor is the last session's ID
  const nextCursor =
    hasMore && resultSessions.length > 0 ? resultSessions[resultSessions.length - 1].id : null
 
  return {
    sessions: practiceSessionsResult,
    nextCursor,
    hasMore,
  }
}
 
// ============================================================================
// COMPOSITE OPERATIONS
// ============================================================================
 
/**
 * Get full progress summary for a player
 */
export interface PlayerProgressSummary {
  curriculum: PlayerCurriculum | null
  totalSkills: number
  /** Number of skills with isPracticing=true */
  practicingSkillCount: number
  /** Percentage of skills being practiced */
  practicingPercent: number
  recentSessions: PracticeSession[]
  recentSkills: PlayerSkillMastery[]
  /** @deprecated Use practicingSkillCount instead */
  masteredSkills: number
  /** @deprecated No longer used - was always 0 */
  practicingSkills: number
  /** @deprecated No longer used */
  learningSkills: number
  /** @deprecated Use practicingPercent instead */
  masteryPercent: number
}
 
export async function getPlayerProgressSummary(playerId: string): Promise<PlayerProgressSummary> {
  const [curriculum, allSkills, recentSessions] = await Promise.all([
    getPlayerCurriculum(playerId),
    getAllSkillMastery(playerId),
    getRecentSessions(playerId, 5),
  ])

  const practicingSkillCount = allSkills.filter((s) => isActive(s.practiceLevel)).length
  const totalSkills = allSkills.length

  const practicingPercent =
    totalSkills > 0 ? Math.round((practicingSkillCount / totalSkills) * 100) : 0

  // Get 5 most recently practiced skills
  const recentSkills = allSkills.slice(0, 5)

  return {
    curriculum,
    totalSkills,
    practicingSkillCount,
    practicingPercent,
    recentSessions,
    recentSkills,
    // Backwards compat - deprecated fields
    masteredSkills: practicingSkillCount,
    practicingSkills: 0,
    learningSkills: totalSkills - practicingSkillCount,
    masteryPercent: practicingPercent,
  }
}
 
/**
 * Initialize a new student in the curriculum
 * Creates curriculum position if it doesn't exist
 */
export async function initializeStudent(playerId: string): Promise<PlayerCurriculum> {
  return upsertPlayerCurriculum(playerId, {
    currentLevel: 1,
    currentPhaseId: 'L1.add.+1.direct',
    visualizationMode: false,
  })
}
 
// ============================================================================
// SKILL PERFORMANCE ANALYSIS
// ============================================================================
 
/**
 * Skill performance data with calculated averages
 */
export interface SkillPerformance {
  skillId: string
  /** BKT-based mastery classification (null = insufficient data, computed client-side) */
  bktClassification: 'strong' | 'developing' | 'weak' | null
  attempts: number
  correct: number
  avgResponseTimeMs: number | null // null if no timing data
  responseTimeCount: number
}
 
/**
 * Analysis of a player's skill strengths and weaknesses
 */
export interface SkillPerformanceAnalysis {
  /** All skills with performance data */
  skills: SkillPerformance[]
  /** Overall average response time (ms) across all skills with timing data */
  overallAvgResponseTimeMs: number | null
  /** Skills where student is significantly faster than average (excelling) */
  fastSkills: SkillPerformance[]
  /** Skills where student is significantly slower than average (struggling) */
  slowSkills: SkillPerformance[]
}
 
/**
 * Thresholds for performance analysis
 */
const PERFORMANCE_THRESHOLDS = {
  /** Speed deviation threshold (percentage faster/slower than average to flag) */
  speedDeviationPercent: 0.3, // 30% faster/slower
  /** Minimum responses needed for timing analysis */
  minResponsesForTiming: 3,
} as const
 
/**
 * Analyze a player's skill performance to identify strengths and weaknesses
 * Uses response time data to find skills where the student excels vs struggles
 *
 * Note: BKT classification is computed client-side from session plan data,
 * so we return null here. The client enriches this with BKT data.
 *
 * Stats (attempts, correct, responseTime) are computed from session results,
 * not from the playerSkillMastery table, ensuring single source of truth.
 */
export async function analyzeSkillPerformance(playerId: string): Promise<SkillPerformanceAnalysis> {
  const allSkills = await getAllSkillMastery(playerId)
  const sessionResults = await getRecentSessionResults(playerId, 100)

  // Aggregate stats per skill from session results
  const skillStats = new Map<
    string,
    { attempts: number; correct: number; responseTimes: number[] }
  >()

  for (const result of sessionResults) {
    for (const skillId of result.skillsExercised) {
      if (!skillStats.has(skillId)) {
        skillStats.set(skillId, { attempts: 0, correct: 0, responseTimes: [] })
      }
      const stats = skillStats.get(skillId)!
      stats.attempts++
      if (result.isCorrect) {
        stats.correct++
      }
      if (result.responseTimeMs > 0) {
        stats.responseTimes.push(result.responseTimeMs)
      }
    }
  }

  // Calculate performance data for each skill
  // Note: bktClassification is computed client-side from session history
  const skills: SkillPerformance[] = allSkills.map((s) => {
    const stats = skillStats.get(s.skillId)
    const attempts = stats?.attempts ?? 0
    const correct = stats?.correct ?? 0
    const responseTimes = stats?.responseTimes ?? []

    return {
      skillId: s.skillId,
      bktClassification: null, // Computed client-side from session plans
      attempts,
      correct,
      avgResponseTimeMs:
        responseTimes.length > 0
          ? Math.round(responseTimes.reduce((a, b) => a + b, 0) / responseTimes.length)
          : null,
      responseTimeCount: responseTimes.length,
    }
  })

  // Calculate overall average response time (only from skills with sufficient data)
  const skillsWithTiming = skills.filter(
    (s) =>
      s.avgResponseTimeMs !== null &&
      s.responseTimeCount >= PERFORMANCE_THRESHOLDS.minResponsesForTiming
  )
  const overallAvgResponseTimeMs =
    skillsWithTiming.length > 0
      ? Math.round(
          skillsWithTiming.reduce((sum, s) => sum + (s.avgResponseTimeMs ?? 0), 0) /
            skillsWithTiming.length
        )
      : null

  // Identify fast skills (significantly faster than average)
  const fastSkills =
    overallAvgResponseTimeMs !== null
      ? skillsWithTiming.filter(
          (s) =>
            s.avgResponseTimeMs !== null &&
            s.avgResponseTimeMs <
              overallAvgResponseTimeMs * (1 - PERFORMANCE_THRESHOLDS.speedDeviationPercent)
        )
      : []

  // Identify slow skills (significantly slower than average)
  const slowSkills =
    overallAvgResponseTimeMs !== null
      ? skillsWithTiming.filter(
          (s) =>
            s.avgResponseTimeMs !== null &&
            s.avgResponseTimeMs >
              overallAvgResponseTimeMs * (1 + PERFORMANCE_THRESHOLDS.speedDeviationPercent)
        )
      : []

  return {
    skills,
    overallAvgResponseTimeMs,
    fastSkills,
    slowSkills,
  }
}
 
/**
 * Get skills ranked by response time (slowest first)
 * Useful for identifying skills that need practice
 */
export async function getSkillsByResponseTime(
  playerId: string,
  order: 'slowest' | 'fastest' = 'slowest'
): Promise<SkillPerformance[]> {
  const analysis = await analyzeSkillPerformance(playerId)

  // Filter to only skills with timing data
  const skillsWithTiming = analysis.skills.filter(
    (s) =>
      s.avgResponseTimeMs !== null &&
      s.responseTimeCount >= PERFORMANCE_THRESHOLDS.minResponsesForTiming
  )

  // Sort by response time
  return skillsWithTiming.sort((a, b) => {
    const timeA = a.avgResponseTimeMs ?? 0
    const timeB = b.avgResponseTimeMs ?? 0
    return order === 'slowest' ? timeB - timeA : timeA - timeB
  })
}
 
// ============================================================================
// SKILL TUTORIAL PROGRESS OPERATIONS
// ============================================================================
 
/**
 * Get a player's tutorial progress for a specific skill
 */
export async function getSkillTutorialProgress(
  playerId: string,
  skillId: string
): Promise<SkillTutorialProgress | null> {
  const result = await db.query.skillTutorialProgress.findFirst({
    where: and(
      eq(schema.skillTutorialProgress.playerId, playerId),
      eq(schema.skillTutorialProgress.skillId, skillId)
    ),
  })
  return result ?? null
}
 
/**
 * Get all tutorial progress records for a player
 */
export async function getAllTutorialProgress(playerId: string): Promise<SkillTutorialProgress[]> {
  return db.query.skillTutorialProgress.findMany({
    where: eq(schema.skillTutorialProgress.playerId, playerId),
  })
}
 
/**
 * Check if a skill's tutorial requirement is satisfied for a player.
 * Returns true if tutorial completed OR teacher override applied.
 */
export async function isSkillTutorialSatisfied(
  playerId: string,
  skillId: string
): Promise<boolean> {
  const progress = await getSkillTutorialProgress(playerId, skillId)
  return isTutorialSatisfied(progress)
}
 
/**
 * Mark a skill's tutorial as completed
 */
export async function markTutorialComplete(
  playerId: string,
  skillId: string
): Promise<SkillTutorialProgress> {
  const existing = await getSkillTutorialProgress(playerId, skillId)
  const now = new Date()

  if (existing) {
    await db
      .update(schema.skillTutorialProgress)
      .set({
        tutorialCompleted: true,
        completedAt: now,
        updatedAt: now,
      })
      .where(eq(schema.skillTutorialProgress.id, existing.id))

    return (await getSkillTutorialProgress(playerId, skillId))!
  }

  // Create new record
  const newRecord: NewSkillTutorialProgress = {
    playerId,
    skillId,
    tutorialCompleted: true,
    completedAt: now,
    createdAt: now,
    updatedAt: now,
  }

  await db.insert(schema.skillTutorialProgress).values(newRecord)
  return (await getSkillTutorialProgress(playerId, skillId))!
}
 
/**
 * Apply teacher override to bypass tutorial requirement.
 * Use case: student learned the technique offline with their teacher.
 */
export async function applyTutorialOverride(
  playerId: string,
  skillId: string,
  reason?: string
): Promise<SkillTutorialProgress> {
  const existing = await getSkillTutorialProgress(playerId, skillId)
  const now = new Date()

  if (existing) {
    await db
      .update(schema.skillTutorialProgress)
      .set({
        teacherOverride: true,
        overrideAt: now,
        overrideReason: reason ?? null,
        updatedAt: now,
      })
      .where(eq(schema.skillTutorialProgress.id, existing.id))

    return (await getSkillTutorialProgress(playerId, skillId))!
  }

  // Create new record
  const newRecord: NewSkillTutorialProgress = {
    playerId,
    skillId,
    teacherOverride: true,
    overrideAt: now,
    overrideReason: reason ?? null,
    createdAt: now,
    updatedAt: now,
  }

  await db.insert(schema.skillTutorialProgress).values(newRecord)
  return (await getSkillTutorialProgress(playerId, skillId))!
}
 
/**
 * Record that a student skipped the tutorial prompt.
 * Used to surface to teachers if student is repeatedly avoiding tutorials.
 */
export async function recordTutorialSkip(
  playerId: string,
  skillId: string
): Promise<SkillTutorialProgress> {
  const existing = await getSkillTutorialProgress(playerId, skillId)
  const now = new Date()

  if (existing) {
    await db
      .update(schema.skillTutorialProgress)
      .set({
        skipCount: existing.skipCount + 1,
        lastSkippedAt: now,
        updatedAt: now,
      })
      .where(eq(schema.skillTutorialProgress.id, existing.id))

    return (await getSkillTutorialProgress(playerId, skillId))!
  }

  // Create new record
  const newRecord: NewSkillTutorialProgress = {
    playerId,
    skillId,
    skipCount: 1,
    lastSkippedAt: now,
    createdAt: now,
    updatedAt: now,
  }

  await db.insert(schema.skillTutorialProgress).values(newRecord)
  return (await getSkillTutorialProgress(playerId, skillId))!
}
 
/**
 * Get skills that have been skipped multiple times (for teacher dashboard).
 * Returns skills where the student has skipped the tutorial 3+ times.
 */
export async function getRepeatedlySkippedTutorials(
  playerId: string,
  minSkipCount: number = 3
): Promise<SkillTutorialProgress[]> {
  const allProgress = await getAllTutorialProgress(playerId)
  return allProgress.filter(
    (p) => p.skipCount >= minSkipCount && !p.tutorialCompleted && !p.teacherOverride
  )
}
 
// Re-export the helper function
export { isTutorialSatisfied }
 
// ============================================================================
// SKILL ACTIVATION OPERATIONS
// ============================================================================
 
/**
 * Enable a single skill for practice at the 'abacus' level (default entry after tutorial).
 * Creates a new skill mastery record if one doesn't exist, or updates to 'abacus' level.
 * Preserves existing 'visual' level if already set higher.
 *
 * @param playerId - The player's ID
 * @param skillId - The skill to enable
 * @returns Updated skill mastery record
 */
export async function enableSkillForPractice(
  playerId: string,
  skillId: string
): Promise<PlayerSkillMastery> {
  const existing = await getSkillMastery(playerId, skillId)
  const now = new Date()

  if (existing) {
    // Only upgrade if currently at 'none' level
    if (existing.practiceLevel === 'none') {
      await db
        .update(schema.playerSkillMastery)
        .set({
          isPracticing: true,
          practiceLevel: 'abacus',
          updatedAt: now,
        })
        .where(eq(schema.playerSkillMastery.id, existing.id))
    }
    return (await getSkillMastery(playerId, skillId))!
  }

  // Create new record with skill enabled for practice at abacus level
  const newRecord: NewPlayerSkillMastery = {
    playerId,
    skillId,
    isPracticing: true,
    practiceLevel: 'abacus',
    lastPracticedAt: now,
  }

  await db.insert(schema.playerSkillMastery).values(newRecord)
  return (await getSkillMastery(playerId, skillId))!
}