All files / web/src/lib/mcp tools.ts

64.94% Statements 769/1184
90.24% Branches 37/41
23.52% Functions 4/17
64.94% Lines 769/1184

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 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 11851x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                       1x 1x 1x 1x         1x 1x 1x 1x                                                               1x 1x 1x 1x                                                                                                                                                   1x 1x 1x 1x                                                         1x 1x 1x 1x                                     1x 1x 1x 1x                                                           1x 1x 1x 1x 1x 1x 1x 1x 48x 48x 48x 1x 1x 1x 1x               1x 1x 1x 1x                                                                                                                                                                       1x 1x 1x 1x                                                                                                     1x 1x 1x 1x                                                                     1x 1x 1x 1x                             1x 1x 1x 1x                           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 1x 1x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x     41x 41x 41x     41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 1x 1x 1x 1x 9x 9x 9x 1x 1x 8x 8x 8x 8x 8x 8x 9x 1x 1x 7x 7x 7x 7x 7x 7x 7x 9x 6x 6x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 5x 5x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 5x 5x 5x 5x  
/**
 * MCP Tool implementations for curriculum data access
 */
 
import { eq, or, inArray, desc, and, gte } from 'drizzle-orm'
import { db, schema } from '@/db'
import { parentChild, worksheetShares } from '@/db/schema'
import type { GameBreakSettings } from '@/db/schema/session-plans'
import { getAllSkillMastery, getRecentSessions } from '@/lib/curriculum/progress-manager'
import {
  getRecentSessionResults,
  generateSessionPlan,
  getActiveSessionPlan,
  approveSessionPlan,
  startSessionPlan,
  completeSessionPlanEarly,
  abandonSessionPlan,
  type EnabledParts,
} from '@/lib/curriculum/session-planner'
import {
  createSessionShare,
  getActiveSharesForSession,
  type ShareDuration,
} from '@/lib/session-share'
import { getShareUrl } from '@/lib/share/urls'
import { generateShareId, isValidShareId } from '@/lib/generateShareId'
import {
  DIFFICULTY_PROFILES,
  DIFFICULTY_PROGRESSION,
  type DifficultyProfile,
} from '@/app/create/worksheets/difficultyProfiles'
import {
  serializeAdditionConfig,
  parseAdditionConfig,
  defaultAdditionConfig,
  type AdditionConfigV4Custom,
} from '@/app/create/worksheets/config-schemas'
import type { DisplayRules, RuleMode } from '@/app/create/worksheets/displayRules'
 
// Tool definitions for MCP tools/list response
export const MCP_TOOLS = [
  {
    name: 'list_students',
    description:
      'List all students (players) accessible to this API key. Returns player IDs, names, and emojis.',
    inputSchema: {
      type: 'object',
      properties: {},
      required: [],
    },
  },
  {
    name: 'get_student_overview',
    description:
      'Get a quick overview of a student including skill counts, last practice date, and current streak.',
    inputSchema: {
      type: 'object',
      properties: {
        player_id: {
          type: 'string',
          description: 'The student player ID',
        },
      },
      required: ['player_id'],
    },
  },
  {
    name: 'get_skills',
    description:
      'Get detailed skill mastery levels for a student. Can filter by status (strong/developing/weak) or category.',
    inputSchema: {
      type: 'object',
      properties: {
        player_id: {
          type: 'string',
          description: 'The student player ID',
        },
        status: {
          type: 'string',
          enum: ['strong', 'developing', 'weak'],
          description: 'Filter by mastery status',
        },
        category: {
          type: 'string',
          description:
            'Filter by skill category (basic, fiveComplements, tenComplements, fiveComplementsSub, tenComplementsSub, advanced)',
        },
      },
      required: ['player_id'],
    },
  },
  {
    name: 'get_recent_errors',
    description:
      'Get recent incorrect answers for a student. Useful for identifying patterns and targeting practice.',
    inputSchema: {
      type: 'object',
      properties: {
        player_id: {
          type: 'string',
          description: 'The student player ID',
        },
        days: {
          type: 'number',
          description: 'Number of days to look back (default: 7)',
        },
        skill_id: {
          type: 'string',
          description: 'Filter to a specific skill ID',
        },
        limit: {
          type: 'number',
          description: 'Maximum number of errors to return (default: 20)',
        },
      },
      required: ['player_id'],
    },
  },
  {
    name: 'get_practice_sessions',
    description:
      'Get recent practice session history showing when and how much a student practiced.',
    inputSchema: {
      type: 'object',
      properties: {
        player_id: {
          type: 'string',
          description: 'The student player ID',
        },
        days: {
          type: 'number',
          description: 'Number of days to look back (default: 14)',
        },
      },
      required: ['player_id'],
    },
  },
  {
    name: 'get_recommended_focus',
    description:
      'Get skill recommendations based on mastery levels. Returns skills that need the most practice.',
    inputSchema: {
      type: 'object',
      properties: {
        player_id: {
          type: 'string',
          description: 'The student player ID',
        },
        count: {
          type: 'number',
          description: 'Number of recommendations to return (default: 5)',
        },
      },
      required: ['player_id'],
    },
  },
  // Session management tools
  {
    name: 'start_practice_session',
    description:
      'Create and optionally start a new practice session for a student. Returns URLs for practice and observation.',
    inputSchema: {
      type: 'object',
      properties: {
        player_id: {
          type: 'string',
          description: 'The student player ID',
        },
        duration_minutes: {
          type: 'number',
          description: 'Session duration in minutes (5-60)',
        },
        auto_start: {
          type: 'boolean',
          description:
            'If true, immediately approve and start the session. If false (default), creates a draft that needs approval.',
        },
        enabled_parts: {
          type: 'object',
          description: 'Which practice parts to enable. Default: all enabled.',
          properties: {
            abacus: {
              type: 'boolean',
              description: 'Physical abacus practice (default: true)',
            },
            visualization: {
              type: 'boolean',
              description: 'Mental math with visualization (default: true)',
            },
            linear: {
              type: 'boolean',
              description: 'Mental math with equations (default: true)',
            },
          },
        },
        max_terms: {
          type: 'number',
          description: 'Maximum terms per problem (3-12, default: 5)',
        },
        game_breaks: {
          type: 'object',
          description: 'Game break settings between session parts',
          properties: {
            enabled: {
              type: 'boolean',
              description: 'Allow game breaks (default: true)',
            },
            max_minutes: {
              type: 'number',
              description: 'Maximum game break duration in minutes (default: 5)',
            },
            selection_mode: {
              type: 'string',
              enum: ['auto-start', 'kid-chooses'],
              description: 'How game is selected (default: kid-chooses)',
            },
          },
        },
      },
      required: ['player_id', 'duration_minutes'],
    },
  },
  {
    name: 'get_active_session',
    description:
      'Get the current active practice session for a student, including URLs for practice and observation.',
    inputSchema: {
      type: 'object',
      properties: {
        player_id: {
          type: 'string',
          description: 'The student player ID',
        },
      },
      required: ['player_id'],
    },
  },
  {
    name: 'control_session',
    description:
      'Control an active session: approve a draft, start an approved session, end early, or abandon.',
    inputSchema: {
      type: 'object',
      properties: {
        player_id: {
          type: 'string',
          description: 'The student player ID',
        },
        session_id: {
          type: 'string',
          description: 'The session plan ID',
        },
        action: {
          type: 'string',
          enum: ['approve', 'start', 'end_early', 'abandon'],
          description: 'Action to perform on the session',
        },
      },
      required: ['player_id', 'session_id', 'action'],
    },
  },
  {
    name: 'create_observation_link',
    description:
      'Generate a shareable URL that allows anyone (without login) to observe a practice session in real-time.',
    inputSchema: {
      type: 'object',
      properties: {
        player_id: {
          type: 'string',
          description: 'The student player ID',
        },
        session_id: {
          type: 'string',
          description: 'The session plan ID',
        },
        expires_in: {
          type: 'string',
          enum: ['1h', '24h'],
          description: 'How long the link should be valid',
        },
      },
      required: ['player_id', 'session_id', 'expires_in'],
    },
  },
  {
    name: 'list_observation_links',
    description: 'List all active (non-expired, non-revoked) observation links for a session.',
    inputSchema: {
      type: 'object',
      properties: {
        player_id: {
          type: 'string',
          description: 'The student player ID',
        },
        session_id: {
          type: 'string',
          description: 'The session plan ID',
        },
      },
      required: ['player_id', 'session_id'],
    },
  },
  // Worksheet generation tools
  {
    name: 'generate_worksheet',
    description:
      'Generate a math worksheet with configurable difficulty, scaffolding, and layout. Returns share and download URLs.',
    inputSchema: {
      type: 'object',
      properties: {
        operator: {
          type: 'string',
          enum: ['addition', 'subtraction', 'mixed'],
          description: 'Type of math operation (default: addition)',
        },
        digit_range: {
          type: 'object',
          description: 'Range of digits per number (default: { min: 2, max: 2 })',
          properties: {
            min: {
              type: 'number',
              description: 'Minimum digits (1-5)',
            },
            max: {
              type: 'number',
              description: 'Maximum digits (1-5)',
            },
          },
        },
        problems_per_page: {
          type: 'number',
          description: 'Number of problems per page (default: 20)',
        },
        pages: {
          type: 'number',
          description: 'Number of pages (default: 1)',
        },
        difficulty_profile: {
          type: 'string',
          enum: ['beginner', 'earlyLearner', 'practice', 'intermediate', 'advanced', 'expert'],
          description: 'Preset difficulty profile that controls regrouping and scaffolding',
        },
        scaffolding: {
          type: 'object',
          description:
            'Custom scaffolding overrides. When provided, these values override the difficulty profile defaults.',
          properties: {
            carryBoxes: {
              type: 'string',
              enum: ['always', 'whenRegrouping', 'whenMultipleRegroups', 'never'],
              description: 'When to show carry boxes for addition',
            },
            answerBoxes: {
              type: 'string',
              enum: ['always', 'whenRegrouping', 'whenMultipleRegroups', 'never'],
              description: 'When to show answer digit boxes',
            },
            placeValueColors: {
              type: 'string',
              enum: [
                'always',
                'whenRegrouping',
                'whenMultipleRegroups',
                'when3PlusDigits',
                'never',
              ],
              description: 'When to color-code place values',
            },
            tenFrames: {
              type: 'string',
              enum: ['always', 'whenRegrouping', 'whenMultipleRegroups', 'never'],
              description: 'When to show ten frames for visual support',
            },
            borrowNotation: {
              type: 'string',
              enum: ['always', 'whenRegrouping', 'never'],
              description: 'When to show borrow notation for subtraction',
            },
            borrowingHints: {
              type: 'string',
              enum: ['always', 'whenRegrouping', 'whenMultipleRegroups', 'never'],
              description: 'When to show borrowing hints for subtraction',
            },
          },
        },
        show_problem_numbers: {
          type: 'boolean',
          description: 'Show problem numbers (1, 2, 3...) next to each problem (default: true)',
        },
        progressive_difficulty: {
          type: 'boolean',
          description:
            'Increase difficulty across pages. Page 1 has lowest regrouping %, last page has highest. Only applies when pages > 1. (default: false)',
        },
        include_answer_key: {
          type: 'boolean',
          description: 'Include answer key pages at end (default: false)',
        },
        title: {
          type: 'string',
          description: 'Optional title for the worksheet',
        },
        orientation: {
          type: 'string',
          enum: ['portrait', 'landscape'],
          description: 'Page orientation (default: landscape)',
        },
        cols: {
          type: 'number',
          description: 'Number of columns (1-6, default: 5)',
        },
      },
      required: [],
    },
  },
  {
    name: 'get_worksheet_info',
    description: 'Get information about an existing shared worksheet by its share ID.',
    inputSchema: {
      type: 'object',
      properties: {
        share_id: {
          type: 'string',
          description: 'The worksheet share ID',
        },
      },
      required: ['share_id'],
    },
  },
  {
    name: 'list_difficulty_profiles',
    description:
      'List all available difficulty profiles with their regrouping and scaffolding settings.',
    inputSchema: {
      type: 'object',
      properties: {},
      required: [],
    },
  },
]
 
/**
 * Get all players accessible to a user (created or linked via parent_child)
 */
export async function listStudents(userId: string) {
  // Get player IDs linked via parent_child table
  const linkedPlayerIds = await db.query.parentChild.findMany({
    where: eq(parentChild.parentUserId, userId),
  })
  const linkedIds = linkedPlayerIds.map((link) => link.childPlayerId)

  // Get all players: created by this user OR linked via parent_child
  let players
  if (linkedIds.length > 0) {
    players = await db.query.players.findMany({
      where: or(eq(schema.players.userId, userId), inArray(schema.players.id, linkedIds)),
      orderBy: (players, { desc }) => [desc(players.createdAt)],
    })
  } else {
    players = await db.query.players.findMany({
      where: eq(schema.players.userId, userId),
      orderBy: (players, { desc }) => [desc(players.createdAt)],
    })
  }

  return players.map((p) => ({
    playerId: p.id,
    name: p.name,
    emoji: p.emoji,
  }))
}
 
/**
 * Verify a player belongs to a user
 */
export async function verifyPlayerAccess(userId: string, playerId: string): Promise<boolean> {
  const students = await listStudents(userId)
  return students.some((s) => s.playerId === playerId)
}
 
/**
 * Get student overview with skill counts and practice info
 */
export async function getStudentOverview(playerId: string) {
  const player = await db.query.players.findFirst({
    where: eq(schema.players.id, playerId),
  })

  if (!player) {
    throw new Error('Player not found')
  }

  const skills = await getAllSkillMastery(playerId)
  const recentSessions = await getRecentSessions(playerId, 30)

  // Count by status
  const strong = skills.filter((s) => s.isPracticing && s.lastPracticedAt).length
  const developing = skills.filter((s) => s.isPracticing && !s.lastPracticedAt).length

  // Find last practice date
  const lastSession = recentSessions[0]
  const lastPracticed = lastSession?.startedAt ?? null

  return {
    playerId: player.id,
    name: player.name,
    emoji: player.emoji,
    lastPracticed,
    totalSkills: skills.length,
    strong,
    developing,
    weak: skills.length - strong - developing,
  }
}
 
/**
 * Get detailed skill data with optional filtering
 */
export async function getSkills(playerId: string, status?: string, category?: string) {
  const rawSkills = await getAllSkillMastery(playerId)
  const sessionResults = await getRecentSessionResults(playerId, 2000)

  // Compute skill stats from session results
  const skillStats = new Map<
    string,
    { attempts: number; correct: number; lastPracticed: Date | null }
  >()

  for (const result of sessionResults) {
    for (const skillId of result.skillsExercised) {
      if (!skillStats.has(skillId)) {
        skillStats.set(skillId, {
          attempts: 0,
          correct: 0,
          lastPracticed: null,
        })
      }
      const stats = skillStats.get(skillId)!
      stats.attempts++
      if (result.isCorrect) {
        stats.correct++
      }
      if (!stats.lastPracticed || result.timestamp > stats.lastPracticed) {
        stats.lastPracticed = result.timestamp
      }
    }
  }

  // Enrich skills with computed stats
  let skills = rawSkills.map((skill) => {
    const stats = skillStats.get(skill.skillId)
    const attempts = stats?.attempts ?? 0
    const correct = stats?.correct ?? 0
    const accuracy = attempts > 0 ? correct / attempts : 0

    // Determine status based on accuracy and attempts
    let computedStatus: 'strong' | 'developing' | 'weak'
    if (attempts >= 5 && accuracy >= 0.9) {
      computedStatus = 'strong'
    } else if (attempts >= 3 && accuracy >= 0.7) {
      computedStatus = 'developing'
    } else {
      computedStatus = 'weak'
    }

    // Parse category from skillId (e.g., "fiveComplements.4=5-1" -> "fiveComplements")
    const skillCategory = skill.skillId.split('.')[0]

    return {
      skillId: skill.skillId,
      displayName: skill.skillId.split('.')[1] || skill.skillId,
      category: skillCategory,
      attempts,
      correct,
      errors: attempts - correct,
      accuracy: Math.round(accuracy * 100),
      lastPracticed: stats?.lastPracticed ?? null,
      status: computedStatus,
    }
  })

  // Apply filters
  if (status) {
    skills = skills.filter((s) => s.status === status)
  }
  if (category) {
    skills = skills.filter((s) => s.category === category)
  }

  return skills
}
 
/**
 * Get recent errors for a student
 */
export async function getRecentErrors(
  playerId: string,
  days: number = 7,
  skillId?: string,
  limit: number = 20
) {
  const cutoffDate = new Date()
  cutoffDate.setDate(cutoffDate.getDate() - days)

  const sessionResults = await getRecentSessionResults(playerId, 2000)

  // Filter to errors only
  let errors = sessionResults
    .filter((r) => !r.isCorrect && r.timestamp >= cutoffDate)
    .map((r) => ({
      timestamp: r.timestamp,
      skillsExercised: r.skillsExercised,
      responseTimeMs: r.responseTimeMs,
    }))

  // Filter by skill if specified
  if (skillId) {
    errors = errors.filter((e) => e.skillsExercised.includes(skillId))
  }

  // Limit results
  return errors.slice(0, limit)
}
 
/**
 * Get practice session history
 */
export async function getPracticeSessions(playerId: string, days: number = 14) {
  const sessions = await getRecentSessions(playerId, 100)

  const cutoffDate = new Date()
  cutoffDate.setDate(cutoffDate.getDate() - days)

  return sessions
    .filter((s) => s.startedAt && s.startedAt >= cutoffDate)
    .map((s) => ({
      date: s.startedAt,
      completedAt: s.completedAt,
      // Duration in minutes if completed
      durationMinutes:
        s.completedAt && s.startedAt
          ? Math.round((s.completedAt.getTime() - s.startedAt.getTime()) / 60000)
          : null,
    }))
}
 
/**
 * Get recommended skills to focus on
 */
export async function getRecommendedFocus(playerId: string, count: number = 5) {
  const skills = await getSkills(playerId)

  // Sort by priority: weak first, then developing, then by lowest accuracy
  const sorted = [...skills].sort((a, b) => {
    // Status priority
    const statusOrder = { weak: 0, developing: 1, strong: 2 }
    const statusDiff = statusOrder[a.status] - statusOrder[b.status]
    if (statusDiff !== 0) return statusDiff

    // Then by accuracy (lower is higher priority)
    return a.accuracy - b.accuracy
  })

  return sorted.slice(0, count).map((skill) => ({
    skillId: skill.skillId,
    displayName: skill.displayName,
    category: skill.category,
    accuracy: skill.accuracy,
    attempts: skill.attempts,
    status: skill.status,
    reason:
      skill.status === 'weak'
        ? 'needs_practice'
        : skill.status === 'developing'
          ? 'close_to_mastery'
          : 'maintenance',
  }))
}
 
// ============================================================================
// Session Management Tools
// ============================================================================
 
/**
 * Get the base URL for generating practice/observation URLs
 */
function getBaseUrl(): string {
  return process.env.NEXT_PUBLIC_APP_URL || 'https://abaci.one'
}
 
/**
 * Build practice and observation URLs for a player
 */
function buildSessionUrls(playerId: string) {
  const baseUrl = getBaseUrl()
  return {
    practiceUrl: `${baseUrl}/practice/${playerId}`,
    observeUrl: `${baseUrl}/practice/${playerId}/observe`,
  }
}
 
/**
 * Start a new practice session for a student
 */
export async function startPracticeSession(
  playerId: string,
  userId: string,
  options: {
    durationMinutes: number
    autoStart?: boolean
    enabledParts?: {
      abacus?: boolean
      visualization?: boolean
      linear?: boolean
    }
    maxTerms?: number
    gameBreaks?: {
      enabled?: boolean
      maxMinutes?: number
      selectionMode?: 'auto-start' | 'kid-chooses'
    }
  }
) {
  const { durationMinutes, autoStart = false, enabledParts, maxTerms, gameBreaks } = options

  // Build enabled parts with defaults
  const parts: EnabledParts = {
    abacus: enabledParts?.abacus ?? true,
    visualization: enabledParts?.visualization ?? true,
    linear: enabledParts?.linear ?? true,
  }

  // Build game break settings
  const gameBreakSettings: GameBreakSettings | undefined = gameBreaks
    ? {
        enabled: gameBreaks.enabled ?? true,
        maxDurationMinutes: gameBreaks.maxMinutes ?? 5,
        selectionMode: gameBreaks.selectionMode ?? 'kid-chooses',
        selectedGame: null,
        skipSetupPhase: true,
      }
    : undefined

  // Generate session plan
  let plan = await generateSessionPlan({
    playerId,
    durationMinutes,
    enabledParts: parts,
    gameBreakSettings,
    ...(maxTerms && {
      config: {
        abacusTermCount: { min: 3, max: maxTerms },
      },
    }),
  })

  // If auto_start, approve and start the session
  if (autoStart) {
    plan = await approveSessionPlan(plan.id)
    plan = await startSessionPlan(plan.id)
  }

  const urls = buildSessionUrls(playerId)

  // Build summary from plan parts
  const partSummaries = plan.parts.map((part) => ({
    partNumber: part.partNumber,
    type: part.type,
    problemCount: part.slots.length,
    estimatedMinutes: part.estimatedMinutes,
  }))

  const totalProblems = plan.parts.reduce((sum, part) => sum + part.slots.length, 0)
  const totalMinutes = plan.parts.reduce((sum, part) => sum + part.estimatedMinutes, 0)

  return {
    sessionId: plan.id,
    status: plan.status,
    practiceUrl: urls.practiceUrl,
    observeUrl: urls.observeUrl,
    summary: {
      totalProblemCount: totalProblems,
      estimatedMinutes: Math.round(totalMinutes),
      parts: partSummaries,
    },
  }
}
 
/**
 * Get the active session for a student
 */
export async function getActiveSession(playerId: string) {
  const plan = await getActiveSessionPlan(playerId)

  if (!plan) {
    // Get last completed session date
    const recentSessions = await getRecentSessions(playerId, 1)
    const lastSession = recentSessions[0]

    return {
      hasActiveSession: false,
      lastSessionAt: lastSession?.completedAt?.getTime() ?? null,
    }
  }

  const urls = buildSessionUrls(playerId)

  // Calculate progress
  const totalProblems = plan.parts.reduce((sum, part) => sum + part.slots.length, 0)
  const completedProblems = plan.results.length
  const correctAnswers = plan.results.filter((r) => r.isCorrect).length
  const accuracy = completedProblems > 0 ? correctAnswers / completedProblems : 0

  // Find current position
  let currentPart = 1
  let currentProblem = 1
  for (const part of plan.parts) {
    const partResults = plan.results.filter((r) => r.partNumber === part.partNumber)
    if (partResults.length < part.slots.length) {
      currentPart = part.partNumber
      currentProblem = partResults.length + 1
      break
    }
  }

  return {
    hasActiveSession: true,
    sessionId: plan.id,
    status: plan.status,
    practiceUrl: urls.practiceUrl,
    observeUrl: urls.observeUrl,
    startedAt: plan.startedAt?.getTime() ?? null,
    progress: {
      currentPart,
      currentProblem,
      totalProblems,
      completedProblems,
      accuracy: Math.round(accuracy * 100),
    },
  }
}
 
/**
 * Control an active session (approve, start, end, abandon)
 */
export async function controlSession(
  playerId: string,
  sessionId: string,
  action: 'approve' | 'start' | 'end_early' | 'abandon'
) {
  let plan
  let message: string

  switch (action) {
    case 'approve':
      plan = await approveSessionPlan(sessionId)
      message = 'Session approved and ready to start'
      break
    case 'start':
      plan = await startSessionPlan(sessionId)
      message = 'Session started'
      break
    case 'end_early':
      plan = await completeSessionPlanEarly(sessionId, 'Ended via MCP')
      message = 'Session ended early'
      break
    case 'abandon':
      plan = await abandonSessionPlan(sessionId)
      message = 'Session abandoned'
      break
  }

  return {
    success: true,
    sessionId: plan.id,
    newStatus: plan.status,
    message,
  }
}
 
/**
 * Create a shareable observation link for a session
 */
export async function createObservationLink(
  playerId: string,
  sessionId: string,
  userId: string,
  expiresIn: ShareDuration
) {
  const share = await createSessionShare(sessionId, playerId, userId, expiresIn)

  return {
    token: share.id,
    url: getShareUrl('observe', share.id),
    expiresAt: share.expiresAt.getTime(),
  }
}
 
/**
 * List active observation links for a session
 */
export async function listObservationLinks(playerId: string, sessionId: string) {
  const shares = await getActiveSharesForSession(sessionId)

  return {
    shares: shares.map((share) => ({
      token: share.id,
      url: getShareUrl('observe', share.id),
      expiresAt: share.expiresAt.getTime(),
      viewCount: share.viewCount,
      createdAt: share.createdAt.getTime(),
    })),
  }
}
 
// ============================================================================
// Worksheet Generation Tools
// ============================================================================
 
/**
 * Scaffolding override options for MCP tool
 */
export interface ScaffoldingOverrides {
  carryBoxes?: RuleMode
  answerBoxes?: RuleMode
  placeValueColors?: RuleMode
  tenFrames?: RuleMode
  borrowNotation?: RuleMode
  borrowingHints?: RuleMode
}
 
/**
 * Generate a worksheet with the given configuration
 * Returns share and download URLs
 */
export async function generateWorksheet(options: {
  operator?: 'addition' | 'subtraction' | 'mixed'
  digitRange?: { min: number; max: number }
  problemsPerPage?: number
  pages?: number
  difficultyProfile?: string
  scaffolding?: ScaffoldingOverrides
  showProblemNumbers?: boolean
  progressiveDifficulty?: boolean
  includeAnswerKey?: boolean
  title?: string
  orientation?: 'portrait' | 'landscape'
  cols?: number
}) {
  const baseUrl = getBaseUrl()
 
  // Build config from options, using defaults
  const {
    operator = 'addition',
    digitRange = { min: 2, max: 2 },
    problemsPerPage = 20,
    pages = 1,
    difficultyProfile = 'earlyLearner',
    scaffolding,
    showProblemNumbers = true,
    progressiveDifficulty = false,
    includeAnswerKey = false,
    title = '',
    orientation = 'landscape',
    cols = 5,
  } = options
 
  // Validate digit range
  const validDigitRange = {
    min: Math.max(1, Math.min(5, digitRange.min || 2)),
    max: Math.max(1, Math.min(5, digitRange.max || 2)),
  }
  if (validDigitRange.min > validDigitRange.max) {
    validDigitRange.max = validDigitRange.min
  }
 
  // Get difficulty profile settings
  const profile = DIFFICULTY_PROFILES[difficultyProfile] || DIFFICULTY_PROFILES.earlyLearner
 
  // Build display rules by merging profile defaults with custom scaffolding overrides
  // Ensure all required fields from DisplayRules interface are present
  const displayRules: DisplayRules = {
    // Start with profile defaults
    carryBoxes: scaffolding?.carryBoxes ?? profile.displayRules.carryBoxes,
    answerBoxes: scaffolding?.answerBoxes ?? profile.displayRules.answerBoxes,
    placeValueColors: scaffolding?.placeValueColors ?? profile.displayRules.placeValueColors,
    tenFrames: scaffolding?.tenFrames ?? profile.displayRules.tenFrames,
    borrowNotation: scaffolding?.borrowNotation ?? profile.displayRules.borrowNotation,
    borrowingHints: scaffolding?.borrowingHints ?? profile.displayRules.borrowingHints,
    // Cell borders from profile or default to 'always'
    cellBorders: profile.displayRules.cellBorders ?? 'always',
    // Problem numbers controlled by explicit parameter
    problemNumbers: showProblemNumbers ? 'always' : 'never',
  }
 
  // Validate pages for progressive difficulty
  const validPages = Math.max(1, Math.min(20, pages))
 
  // Build worksheet config
  const config: AdditionConfigV4Custom = {
    version: 4,
    mode: 'custom',
    operator,
    digitRange: validDigitRange,
    problemsPerPage: Math.max(1, Math.min(40, problemsPerPage)),
    pages: validPages,
    cols: Math.max(1, Math.min(6, cols)),
    orientation,
    name: title,
    fontSize: 16,
    pAnyStart: profile.regrouping.pAnyStart,
    pAllStart: profile.regrouping.pAllStart,
    // Use interpolate for progressive difficulty (problems get harder through worksheet)
    interpolate: progressiveDifficulty,
    displayRules,
    difficultyProfile: profile.name,
    includeAnswerKey,
    includeQRCode: true, // Always include QR code for MCP-generated worksheets
    seed: Math.floor(Math.random() * 1000000), // Random seed for unique problems
    // Store progressive difficulty flag for per-page regrouping calculation
    ...(progressiveDifficulty && validPages > 1 && { progressiveDifficulty: true }),
  }
 
  // Generate unique share ID
  let shareId = generateShareId()
  let attempts = 0
  const MAX_ATTEMPTS = 5
  let isUnique = false
 
  while (!isUnique && attempts < MAX_ATTEMPTS) {
    shareId = generateShareId()
    const existing = await db.query.worksheetShares.findFirst({
      where: eq(worksheetShares.id, shareId),
    })
 
    if (!existing) {
      isUnique = true
    } else {
      attempts++
    }
  }
 
  if (!isUnique) {
    throw new Error('Failed to generate unique share ID')
  }
 
  // Serialize config
  const configJson = serializeAdditionConfig(config)
 
  // Create share record
  await db.insert(worksheetShares).values({
    id: shareId,
    worksheetType: 'addition',
    config: configJson,
    createdAt: new Date(),
    views: 0,
    creatorIp: 'mcp', // Mark as MCP-generated
    title: title || null,
  })
 
  // Build URLs
  const shareUrl = `${baseUrl}/worksheets/shared/${shareId}`
  const downloadUrl = `${baseUrl}/api/worksheets/download/${shareId}`
 
  // Build summary
  const totalProblems = config.problemsPerPage * config.pages
  const summary = {
    shareId,
    operator: config.operator,
    digitRange: config.digitRange,
    totalProblems,
    pages: config.pages,
    problemsPerPage: config.problemsPerPage,
    cols: config.cols,
    orientation: config.orientation,
    difficultyProfile: profile.name,
    difficultyLabel: profile.label,
    regroupingPercent: Math.round(profile.regrouping.pAnyStart * 100),
    includeAnswerKey: config.includeAnswerKey,
    progressiveDifficulty: progressiveDifficulty && validPages > 1,
    showProblemNumbers,
    scaffolding: {
      carryBoxes: displayRules.carryBoxes,
      answerBoxes: displayRules.answerBoxes,
      placeValueColors: displayRules.placeValueColors,
      tenFrames: displayRules.tenFrames,
      borrowNotation: displayRules.borrowNotation,
      borrowingHints: displayRules.borrowingHints,
      problemNumbers: displayRules.problemNumbers,
    },
  }
 
  return {
    shareId,
    shareUrl,
    downloadUrl,
    summary,
  }
}
 
/**
 * Get information about an existing shared worksheet
 */
export async function getWorksheetInfo(shareId: string) {
  // Validate ID format
  if (!isValidShareId(shareId)) {
    throw new Error('Invalid share ID format')
  }
 
  // Fetch share record
  const share = await db.query.worksheetShares.findFirst({
    where: eq(worksheetShares.id, shareId),
  })
 
  if (!share) {
    throw new Error('Worksheet not found')
  }
 
  // Parse config
  const config = parseAdditionConfig(share.config)
  const baseUrl = getBaseUrl()
 
  // Find matching difficulty profile
  let matchedProfile: DifficultyProfile | undefined
  if (config.mode === 'custom' && config.difficultyProfile) {
    matchedProfile = DIFFICULTY_PROFILES[config.difficultyProfile]
  }
 
  const totalProblems = config.problemsPerPage * config.pages
 
  return {
    shareId: share.id,
    shareUrl: `${baseUrl}/worksheets/shared/${share.id}`,
    downloadUrl: `${baseUrl}/api/worksheets/download/${share.id}`,
    title: share.title,
    worksheetType: share.worksheetType,
    createdAt: share.createdAt.toISOString(),
    views: share.views,
    config: {
      operator: config.operator,
      digitRange: config.digitRange,
      totalProblems,
      pages: config.pages,
      problemsPerPage: config.problemsPerPage,
      cols: config.cols,
      orientation: config.orientation,
      difficultyProfile: matchedProfile?.name || 'custom',
      difficultyLabel: matchedProfile?.label || 'Custom',
      regroupingPercent: Math.round(config.pAnyStart * 100),
      includeAnswerKey: config.includeAnswerKey || false,
    },
  }
}
 
/**
 * List all available difficulty profiles
 */
export function listDifficultyProfiles() {
  return {
    profiles: DIFFICULTY_PROGRESSION.map((name) => {
      const profile = DIFFICULTY_PROFILES[name]
      return {
        name: profile.name,
        label: profile.label,
        description: profile.description,
        regrouping: {
          pAnyStart: profile.regrouping.pAnyStart,
          pAllStart: profile.regrouping.pAllStart,
          percent: Math.round(profile.regrouping.pAnyStart * 100),
        },
        scaffolding: {
          carryBoxes: profile.displayRules.carryBoxes,
          answerBoxes: profile.displayRules.answerBoxes,
          placeValueColors: profile.displayRules.placeValueColors,
          tenFrames: profile.displayRules.tenFrames,
          borrowNotation: profile.displayRules.borrowNotation,
          borrowingHints: profile.displayRules.borrowingHints,
        },
      }
    }),
    progression: DIFFICULTY_PROGRESSION,
  }
}