All files / web/src/lib/curriculum session-planner.ts

21.93% Statements 507/2311
88% Branches 22/25
10.81% Functions 4/37
21.93% Lines 507/2311

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 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 23122x 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 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 7x 7x 7x 7x 2x 2x 2x 2x 2x 2x 2x 2x 2x 6x 6x 6x 6x 6x 6x 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 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 14x 14x 14x 14x 14x 14x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 14x 17x 16x 17x 17x 14x 14x 14x 17x 11x 11x 11x 14x 14x 17x 17x 17x 17x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 14x 13x 13x 14x 11x 11x 13x 13x 13x 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 2x 2x 2x 2x 2x 2x 2x 2x                                                   2x 2x 2x 2x 2x                                                                                                 2x                 2x 2x 2x 2x                     2x                                                  
/**
 * Session Planner - Generates adaptive practice session plans
 *
 * Creates a three-part plan based on:
 * - Part 1: Abacus practice (use physical abacus, vertical format)
 * - Part 2: Visualization (mental math by picturing beads, vertical format)
 * - Part 3: Linear (mental math in sentence format, e.g., "45 + 27 = ?")
 *
 * Each part's duration is based on configured weights.
 * Skills and difficulty are determined by:
 * - Student's current curriculum position
 * - Skill mastery levels (what needs work vs. what's mastered)
 * - Spaced repetition needs (when skills were last practiced)
 */
 
import { createId } from '@paralleldrive/cuid2'
import { and, desc, eq, inArray, isNull, sql } from 'drizzle-orm'
import { db, schema } from '@/db'
import { isActive, isVisualReady, type PlayerSkillMastery } from '@/db/schema/player-skill-mastery'
import type { GameResultsReport } from '@/lib/arcade/game-sdk/types'
import {
  calculateMasteryWeight,
  calculateSessionHealth,
  DEFAULT_GAME_BREAK_SETTINGS,
  DEFAULT_PLAN_CONFIG,
  type GameBreakSettings,
  initRetryState,
  isInRetryEpoch,
  MAX_RETRY_EPOCHS,
  type NewSessionPlan,
  type PartSummary,
  type PlanGenerationConfig,
  type ProblemSlot,
  type SessionHealth,
  type SessionPart,
  type SessionFlowState,
  type SessionPartType,
  type SessionPlan,
  type SessionRetryState,
  type SessionSummary,
  type SlotResult,
} from '@/db/schema/session-plans'
import {
  buildStudentSkillHistoryFromRecords,
  calculateMaxSkillCost,
  createSkillCostCalculator,
  type SkillCostCalculator,
} from '@/utils/skillComplexity'
import { computeBktFromHistory, type SkillBktResult } from './bkt'
import {
  BKT_INTEGRATION_CONFIG,
  DEFAULT_PROBLEM_GENERATION_MODE,
  MIN_SECONDS_PER_PROBLEM,
  WEAK_SKILL_THRESHOLDS,
  type ProblemGenerationMode,
} from './config'
import {
  type CurriculumPhase,
  getPhase,
  getPhaseDisplayInfo,
  type getPhaseSkillConstraints,
} from './definitions'
import { generateProblemFromConstraints } from './problem-generator'
import {
  getAllSkillMastery,
  getPlayerCurriculum,
  getRecentSessions,
  recordSkillAttemptsWithHelp,
} from './progress-manager'
import { getWeakSkillIds, type SessionMode } from './session-mode'
import { revokeSharesForSession } from '@/lib/session-share'
import {
  computeComfortLevel,
  computeComfortLevelByMode,
  applyTermCountOverride,
} from './comfort-level'
import {
  computeTermCountRange,
  parseTermCountScaling,
  type TermCountExplanation,
  type TermCountScalingConfig,
} from './config/term-count-scaling'
import { appSettings } from '@/db/schema'
import { applyFlowEvent, type SessionFlowEvent } from './session-flow'
 
// ============================================================================
// Plan Generation
// ============================================================================
 
/**
 * Which session parts to include in the generated plan
 */
export interface EnabledParts {
  abacus: boolean
  visualization: boolean
  linear: boolean
}
 
export interface GenerateSessionPlanOptions {
  playerId: string
  durationMinutes: number
  config?: Partial<PlanGenerationConfig>
  enabledParts?: EnabledParts
  confidenceThreshold?: number
  problemGenerationMode?: ProblemGenerationMode
  sessionMode?: SessionMode
  gameBreakSettings?: GameBreakSettings
  /** Override the number of problems per part (for debug/testing) */
  overrideProblemsPerPart?: number
  /** When true, shuffle problem purposes within each part (default: true) */
  shufflePurposes?: boolean
  /** Comfort level adjustment from problem length preference (shorter=-0.3, recommended=0, longer=+0.2) */
  comfortAdjustment?: number
  /** Optional progress callback for background task integration */
  onProgress?: (event: SessionPlanProgressEvent) => void
}
 
/** Progress events emitted during session plan generation */
export type SessionPlanProgressEvent =
  | { type: 'plan_loading_data'; message: string }
  | { type: 'plan_analyzing_skills'; message: string; skillCount: number }
  | {
      type: 'plan_structure_ready'
      message: string
      parts: Array<{ type: string; problemCount: number }>
    }
  | {
      type: 'plan_generating_problem'
      partType: string
      partLabel: string
      current: number
      total: number
    }
  | { type: 'plan_part_complete'; partType: string; problemCount: number; durationMs: number }
  | { type: 'plan_saving'; message: string }
  | {
      type: 'plan_complete'
      planId: string
      timing: {
        totalMs: number
        loadDataMs: number
        bktMs: number
        parts: Array<{
          type: string
          totalMs: number
          problemCount: number
          avgProblemMs: number
        }>
        saveMs: number
      }
    }
 
/**
 * Error thrown when a player already has an active session
 */
export class ActiveSessionExistsError extends Error {
  code = 'ACTIVE_SESSION_EXISTS' as const
  existingSession: SessionPlan
 
  constructor(existingSession: SessionPlan) {
    super('An active session already exists for this player')
    this.name = 'ActiveSessionExistsError'
    this.existingSession = existingSession
  }
}
 
/**
 * Error thrown when trying to generate a session for a student with no skills enabled
 */
export class NoSkillsEnabledError extends Error {
  code = 'NO_SKILLS_ENABLED' as const
 
  constructor() {
    super(
      'Cannot generate a practice session: no skills are enabled for this student. ' +
        'Please enable at least one skill in the skill selector before starting a session.'
    )
    this.name = 'NoSkillsEnabledError'
  }
}
 
/**
 * Generate a three-part session plan for a student
 *
 * @throws {ActiveSessionExistsError} If the player already has an active session that hasn't timed out
 * @throws {NoSkillsEnabledError} If the player has no skills enabled for practice
 */
export async function generateSessionPlan(
  options: GenerateSessionPlanOptions
): Promise<SessionPlan> {
  const {
    playerId,
    durationMinutes,
    config: configOverrides,
    enabledParts,
    problemGenerationMode = DEFAULT_PROBLEM_GENERATION_MODE,
    sessionMode,
    gameBreakSettings = DEFAULT_GAME_BREAK_SETTINGS,
    overrideProblemsPerPart,
    shufflePurposes = true,
    comfortAdjustment = 0,
    onProgress,
  } = options

  const totalStartTime = performance.now()
  const config = { ...DEFAULT_PLAN_CONFIG, ...configOverrides }

  // Default: all parts enabled
  const partsToInclude: EnabledParts = enabledParts ?? {
    abacus: true,
    visualization: true,
    linear: true,
  }

  // Check for existing active session (one active session per kid rule)
  const existingActive = await getActiveSessionPlan(playerId)
  if (existingActive) {
    const sessionAgeMs = Date.now() - new Date(existingActive.createdAt).getTime()
    const timeoutMs = config.sessionTimeoutHours * 60 * 60 * 1000

    if (sessionAgeMs > timeoutMs) {
      // Session has timed out - auto-abandon it
      await abandonSessionPlan(existingActive.id)
    } else {
      // Session is still active - throw error with session data
      throw new ActiveSessionExistsError(existingActive)
    }
  }

  onProgress?.({ type: 'plan_loading_data', message: 'Loading student data...' })

  // 1. Load student state and app config (in parallel for performance)
  const loadDataStart = performance.now()
  const [curriculum, skillMastery, recentSessions, problemHistory, dbSettings] = await Promise.all([
    getPlayerCurriculum(playerId),
    getAllSkillMastery(playerId),
    getRecentSessions(playerId, 10),
    // Only load problem history for BKT in adaptive modes
    problemGenerationMode === 'adaptive' || problemGenerationMode === 'adaptive-bkt'
      ? getRecentSessionResults(playerId, BKT_INTEGRATION_CONFIG.sessionHistoryDepth)
      : Promise.resolve([]),
    // Load term count scaling config from DB
    db.select().from(appSettings).where(eq(appSettings.id, 'default')).limit(1),
  ])

  const loadDataMs = performance.now() - loadDataStart

  // Parse DB term count scaling config (falls back to defaults if null/invalid)
  const termCountScalingConfig = parseTermCountScaling(dbSettings[0]?.termCountScaling ?? null)

  // Compute BKT if in adaptive modes and we have problem history
  const bktStart = performance.now()
  let bktResults: Map<string, SkillBktResult> | undefined
  let byModeBkt: ReturnType<typeof computeBktFromHistory>['byMode']
  const usesBktTargeting =
    problemGenerationMode === 'adaptive' || problemGenerationMode === 'adaptive-bkt'
  if (usesBktTargeting && problemHistory.length > 0) {
    const bktResult = computeBktFromHistory(problemHistory)
    bktResults = new Map(bktResult.skills.map((s) => [s.skillId, s]))
    byModeBkt = bktResult.byMode

    // Debug: Log BKT usage
    if (process.env.DEBUG_SESSION_PLANNER === 'true') {
      console.log(
        `[SessionPlanner] Mode: ${problemGenerationMode}, BKT skills: ${bktResult.skills.length}`
      )
      for (const skill of bktResult.skills.slice(0, 3)) {
        console.log(
          `  ${skill.skillId}: pKnown=${(skill.pKnown * 100).toFixed(0)}%, ` +
            `confidence=${skill.confidence.toFixed(2)}, opportunities=${skill.opportunities}`
        )
      }
    }
  } else if (process.env.DEBUG_SESSION_PLANNER === 'true') {
    console.log(
      `[SessionPlanner] Mode: ${problemGenerationMode}, no BKT (usesBktTargeting=${usesBktTargeting}, history=${problemHistory.length})`
    )
  }

  const bktMs = performance.now() - bktStart

  const practicingCount = skillMastery.filter((s) => isActive(s.practiceLevel)).length
  onProgress?.({
    type: 'plan_analyzing_skills',
    message: `Analyzing ${practicingCount} skill${practicingCount !== 1 ? 's' : ''}...`,
    skillCount: practicingCount,
  })

  // Build student-aware cost calculator for complexity budgeting
  const studentHistory = buildStudentSkillHistoryFromRecords(skillMastery)
  const costCalculator = createSkillCostCalculator(studentHistory, {
    bktResults,
    mode: problemGenerationMode,
  })

  // Debug: Show multipliers for all modes (not just when BKT data exists)
  if (process.env.DEBUG_SESSION_PLANNER === 'true') {
    console.log(`[SessionPlanner] Multiplier comparison (mode=${problemGenerationMode}):`)
    const practicingIds = skillMastery
      .filter((s) => isActive(s.practiceLevel))
      .map((s) => s.skillId)
    for (const skillId of practicingIds.slice(0, 5)) {
      const multiplier = costCalculator.getMultiplier(skillId)
      const isPracticing = costCalculator.getIsPracticing(skillId)
      const bkt = costCalculator.getBktResult(skillId)
      console.log(
        `  ${skillId}: mult=${multiplier.toFixed(2)} inRotation=${isPracticing} ` +
          `bkt_pKnown=${bkt?.pKnown.toFixed(2) ?? 'N/A'} bkt_conf=${bkt?.confidence.toFixed(2) ?? 'N/A'}`
      )
    }
  }

  // Calculate max skill cost for dynamic visualization budget
  // This ensures the student's most expensive skill can appear in visualization
  const practicingSkillIds = skillMastery
    .filter((s) => isActive(s.practiceLevel))
    .map((s) => s.skillId)
  const studentMaxSkillCost = calculateMaxSkillCost(costCalculator, practicingSkillIds)

  // Compute comfort level for dynamic term count scaling
  const rawComfortResult = sessionMode
    ? computeComfortLevel(bktResults, practicingSkillIds, sessionMode)
    : {
        comfortLevel: 0.3,
        factors: {
          avgMastery: null,
          sessionMode: 'maintenance',
          modeMultiplier: 1.0,
          skillCountBonus: 0,
        } as TermCountExplanation['factors'],
      }

  // Compute per-mode comfort levels
  const comfortByMode = sessionMode
    ? computeComfortLevelByMode(byModeBkt, practicingSkillIds, sessionMode)
    : undefined

  // Apply comfort adjustment from problem length preference
  const rawComfortLevel = rawComfortResult.comfortLevel
  const adjustedComfortLevel = Math.max(0, Math.min(1, rawComfortLevel + comfortAdjustment))
  const comfortResult = {
    ...rawComfortResult,
    comfortLevel: adjustedComfortLevel,
  }

  if (process.env.DEBUG_SESSION_PLANNER === 'true') {
    console.log(
      `[SessionPlanner] Comfort level: ${(comfortResult.comfortLevel * 100).toFixed(0)}% ` +
        `(raw=${(rawComfortLevel * 100).toFixed(0)}%, adj=${comfortAdjustment}, ` +
        `avgMastery=${comfortResult.factors.avgMastery?.toFixed(2) ?? 'N/A'}, ` +
        `mode=${comfortResult.factors.sessionMode}, mult=${comfortResult.factors.modeMultiplier}, ` +
        `bonus=${comfortResult.factors.skillCountBonus.toFixed(3)})`
    )
  }

  // Get current phase
  const currentPhaseId = curriculum?.currentPhaseId || 'L1.add.+1.direct'
  const currentPhase = getPhase(currentPhaseId)

  // 2. Calculate personalized timing
  // Clamp to MIN_SECONDS_PER_PROBLEM to prevent generating excessive problems
  // when student timing data is anomalously low (see session-timing.ts for rationale)
  const avgTimeSeconds = Math.max(
    MIN_SECONDS_PER_PROBLEM,
    calculateAvgTimePerProblem(recentSessions) || config.defaultSecondsPerProblem
  )

  // 3. Build skill constraints from the student's ACTUAL practicing skills
  //    Two constraint sets: one for abacus parts (all active skills) and one for
  //    visualization/linear parts (only visual-ready skills)
  const activeSkills = skillMastery.filter((s) => isActive(s.practiceLevel))
  const visualReadySkills = skillMastery.filter((s) => isVisualReady(s.practiceLevel))

  // Cannot generate a session without any skills enabled
  if (activeSkills.length === 0) {
    throw new NoSkillsEnabledError()
  }

  const abacusConstraints = buildConstraintsFromPracticingSkills(activeSkills)
  const visualConstraints =
    visualReadySkills.length > 0
      ? buildConstraintsFromPracticingSkills(visualReadySkills)
      : abacusConstraints // Fallback: if no visual skills, use abacus constraints

  // Legacy alias for compatibility within this function
  const practicingSkillConstraints = abacusConstraints

  // Find skills needing spaced repetition review
  const needsReview = findSkillsNeedingReview(skillMastery, config.reviewIntervalDays)

  // Identify weak skills for targeting
  // When sessionMode is provided, use its pre-computed weak skills (single source of truth)
  // This ensures the session targets exactly what was shown in the UI (no "rug-pulling")
  let weakSkills: string[]
  if (sessionMode) {
    // Use pre-computed weak skills from sessionMode
    weakSkills = getWeakSkillIds(sessionMode)
    if (process.env.DEBUG_SESSION_PLANNER === 'true') {
      console.log(
        `[SessionPlanner] Using weak skills from sessionMode (${sessionMode.type}): ${weakSkills.length}`
      )
    }
  } else {
    // Fallback: compute locally (for backwards compatibility)
    weakSkills = usesBktTargeting ? identifyWeakSkills(bktResults) : []
  }

  if (process.env.DEBUG_SESSION_PLANNER === 'true' && weakSkills.length > 0) {
    console.log(`[SessionPlanner] Targeting ${weakSkills.length} weak skills:`)
    for (const skillId of weakSkills) {
      const bkt = bktResults?.get(skillId)
      console.log(`  ${skillId}: pKnown=${(bkt?.pKnown ?? 0 * 100).toFixed(0)}%`)
    }
  }

  // 4. Build parts using STUDENT'S MASTERED SKILLS (only enabled parts)
  // Auto-disable visualization/linear parts when no visual-ready skills exist
  const hasVisualSkills = visualReadySkills.length > 0
  const enabledPartTypes = (['abacus', 'visualization', 'linear'] as const).filter(
    (type) => partsToInclude[type] && (type === 'abacus' || hasVisualSkills)
  )
  const totalEnabledWeight = enabledPartTypes.reduce(
    (sum, type) => sum + config.partTimeWeights[type],
    0
  )

  // Build slot structures (without problems) first to report structure
  const partSlotStructures: Array<{
    partType: SessionPartType
    normalizedWeight: number
    adjustedModeComfortLevel: number
    modeComfortFactors: TermCountExplanation['factors']
    rawModeComfortLevel: number
  }> = []

  for (const partType of enabledPartTypes) {
    const normalizedWeight = config.partTimeWeights[partType] / totalEnabledWeight
    const modeComfort = comfortByMode?.[partType] ?? rawComfortResult
    const rawModeComfortLevel = modeComfort.comfortLevel
    const adjustedModeComfortLevel = Math.max(
      0,
      Math.min(1, rawModeComfortLevel + comfortAdjustment)
    )

    partSlotStructures.push({
      partType,
      normalizedWeight,
      adjustedModeComfortLevel,
      modeComfortFactors: modeComfort.factors,
      rawModeComfortLevel,
    })
  }

  // Build only enabled parts with normalized time weights
  const parts: SessionPart[] = []
  let partNumber = 1 as 1 | 2 | 3
  const partTimings: Array<{
    type: string
    totalMs: number
    problemCount: number
    avgProblemMs: number
  }> = []

  // Build slot structures first (fast) to get problem counts for progress reporting
  const previewParts: Array<{ type: string; problemCount: number }> = []
  for (const { partType, normalizedWeight } of partSlotStructures) {
    const partDurationMinutes = durationMinutes * normalizedWeight
    const partProblemCount =
      overrideProblemsPerPart ??
      Math.max(2, Math.floor((partDurationMinutes * 60) / avgTimeSeconds))
    previewParts.push({ type: partType, problemCount: partProblemCount })
  }

  onProgress?.({
    type: 'plan_structure_ready',
    message: `Generating ${previewParts.reduce((s, p) => s + p.problemCount, 0)} problems...`,
    parts: previewParts,
  })

  const PART_TYPE_LABELS: Record<string, string> = {
    abacus: 'Abacus',
    visualization: 'Visualization',
    linear: 'Linear',
  }

  for (const {
    partType,
    normalizedWeight,
    adjustedModeComfortLevel,
    modeComfortFactors,
    rawModeComfortLevel,
  } of partSlotStructures) {
    const partStartTime = performance.now()

    // Use visual constraints for visualization/linear parts, abacus constraints for abacus parts
    const partConstraints = partType === 'abacus' ? abacusConstraints : visualConstraints

    const part = await buildSessionPartAsync(
      partNumber,
      partType,
      durationMinutes,
      avgTimeSeconds,
      {
        ...config,
        partTimeWeights: {
          ...config.partTimeWeights,
          [partType]: normalizedWeight,
        },
      },
      partConstraints,
      needsReview,
      currentPhase,
      normalizedWeight,
      costCalculator,
      studentMaxSkillCost,
      weakSkills,
      overrideProblemsPerPart,
      shufflePurposes,
      adjustedModeComfortLevel,
      modeComfortFactors,
      comfortAdjustment,
      rawModeComfortLevel,
      termCountScalingConfig,
      onProgress
        ? (current, total) => {
            onProgress({
              type: 'plan_generating_problem',
              partType,
              partLabel: PART_TYPE_LABELS[partType] ?? partType,
              current,
              total,
            })
          }
        : undefined
    )

    parts.push(part)

    const partMs = performance.now() - partStartTime
    partTimings.push({
      type: partType,
      totalMs: partMs,
      problemCount: part.slots.length,
      avgProblemMs: part.slots.length > 0 ? partMs / part.slots.length : 0,
    })

    onProgress?.({
      type: 'plan_part_complete',
      partType,
      problemCount: part.slots.length,
      durationMs: partMs,
    })

    partNumber = (partNumber + 1) as 1 | 2 | 3
  }

  // 5. Build summary
  const summary = buildSummary(parts, currentPhase, durationMinutes)

  // 6. Calculate total problems
  const totalProblemCount = parts.reduce((sum, part) => sum + part.slots.length, 0)

  onProgress?.({ type: 'plan_saving', message: 'Saving session plan...' })
  const saveStart = performance.now()

  const plan: NewSessionPlan = {
    id: createId(),
    playerId,
    targetDurationMinutes: durationMinutes,
    estimatedProblemCount: totalProblemCount,
    avgTimePerProblemSeconds: avgTimeSeconds,
    gameBreakSettings,
    parts,
    summary,
    masteredSkillIds: activeSkills.map((s) => s.skillId),
    status: 'draft',
    currentPartIndex: 0,
    currentSlotIndex: 0,
    sessionHealth: null,
    adjustments: [],
    results: [],
    createdAt: new Date(),
  }

  const [savedPlan] = await db.insert(schema.sessionPlans).values(plan).returning()

  const saveMs = performance.now() - saveStart
  const totalMs = performance.now() - totalStartTime

  const timing = {
    totalMs,
    loadDataMs,
    bktMs,
    parts: partTimings,
    saveMs,
  }

  if (process.env.DEBUG_SESSION_PLANNER === 'true') {
    console.log(
      `[SessionPlanner] Timing: total=${totalMs.toFixed(0)}ms, ` +
        `loadData=${loadDataMs.toFixed(0)}ms, bkt=${bktMs.toFixed(0)}ms, ` +
        `save=${saveMs.toFixed(0)}ms`
    )
    for (const pt of partTimings) {
      console.log(
        `  ${pt.type}: ${pt.totalMs.toFixed(0)}ms (${pt.problemCount} problems, ` +
          `avg ${pt.avgProblemMs.toFixed(1)}ms/problem)`
      )
    }
  }

  onProgress?.({
    type: 'plan_complete',
    planId: savedPlan.id,
    timing,
  })

  return savedPlan
}
 
/**
 * Build a single session part with the appropriate slots
 *
 * @param weakSkills - Skills identified by BKT as weak (low P(known)).
 *   These are used for both focus and reinforce slots to prioritize practice.
 */
function buildSessionPart(
  partNumber: 1 | 2 | 3,
  type: SessionPartType,
  totalDurationMinutes: number,
  avgTimeSeconds: number,
  config: PlanGenerationConfig,
  phaseConstraints: ReturnType<typeof getPhaseSkillConstraints>,
  needsReview: PlayerSkillMastery[],
  currentPhase: CurriculumPhase | undefined,
  normalizedWeight?: number,
  costCalculator?: SkillCostCalculator,
  studentMaxSkillCost?: number,
  weakSkills?: string[],
  overrideProblemsPerPart?: number,
  shufflePurposes = true,
  comfortLevel = 0.3,
  comfortFactors?: TermCountExplanation['factors'],
  comfortAdjustment?: number,
  rawComfortLevel?: number,
  termCountScalingConfig?: TermCountScalingConfig
): SessionPart {
  // Get time allocation for this part (use normalized weight if provided)
  const partWeight = normalizedWeight ?? config.partTimeWeights[type]
  const partDurationMinutes = totalDurationMinutes * partWeight
  const partProblemCount =
    overrideProblemsPerPart ?? Math.max(2, Math.floor((partDurationMinutes * 60) / avgTimeSeconds))

  // Calculate slot distribution using unified 4-weight proportional allocation.
  //
  // IMPORTANT: Challenge slots require min complexity budget of 1.
  // Basic skills have cost 0, so students with ONLY basic skills can't generate challenge problems.
  // When canDoChallenge is false, challenge weight is set to 0 and its share
  // automatically redistributes to the other 3 purposes via normalization.
  const challengeMinBudget = config.purposeComplexityBounds.challenge[type].min ?? 0
  const canDoChallenge =
    studentMaxSkillCost !== undefined && studentMaxSkillCost >= challengeMinBudget

  const weights = {
    focus: config.focusWeight,
    reinforce: config.reinforceWeight,
    review: config.reviewWeight,
    challenge: canDoChallenge ? (config.challengeWeight ?? 0.2) : 0,
  }
  const totalWeight = weights.focus + weights.reinforce + weights.review + weights.challenge

  const focusCount = Math.round((partProblemCount * weights.focus) / totalWeight)
  const reinforceCount = Math.round((partProblemCount * weights.reinforce) / totalWeight)
  const reviewCount = Math.round((partProblemCount * weights.review) / totalWeight)
  // Challenge absorbs rounding remainder (clamped to 0 if canDoChallenge is false)
  const challengeCount = canDoChallenge
    ? Math.max(0, partProblemCount - focusCount - reinforceCount - reviewCount)
    : 0
  // If no challenge, give remainder to focus
  const adjustedFocusCount =
    focusCount + (canDoChallenge ? 0 : partProblemCount - focusCount - reinforceCount - reviewCount)

  // Build slots
  const slots: ProblemSlot[] = []

  // Build constraints for focus slots that prioritize weak skills
  // This adds BKT-identified weak skills to targetSkills so problem generator prefers them
  const focusConstraints =
    weakSkills && weakSkills.length > 0
      ? addWeakSkillsToTargets(phaseConstraints, weakSkills)
      : phaseConstraints

  if (process.env.DEBUG_SESSION_PLANNER === 'true' && weakSkills && weakSkills.length > 0) {
    const targetSkillsList = Object.entries(focusConstraints.targetSkills || {}).flatMap(
      ([cat, skills]) =>
        Object.entries(skills)
          .filter(([, v]) => v)
          .map(([s]) => `${cat}.${s}`)
    )
    console.log(`[SessionPlanner] Focus slots will target: ${targetSkillsList.join(', ')}`)
  }

  // Focus slots: current phase, primary skill (with weak skill targeting)
  // Uses adjustedFocusCount which includes redistributed challenge slots for basic-skill-only students
  for (let i = 0; i < adjustedFocusCount; i++) {
    slots.push(
      createSlot(
        slots.length,
        'focus',
        focusConstraints,
        type,
        config,
        costCalculator,
        studentMaxSkillCost,
        comfortLevel,
        comfortFactors,
        comfortAdjustment,
        rawComfortLevel,
        termCountScalingConfig
      )
    )
  }

  // Reinforce slots: weak skills (from BKT) get extra practice
  // Uses same targeting as focus slots - problems that exercise weak skills
  for (let i = 0; i < reinforceCount; i++) {
    slots.push(
      createSlot(
        slots.length,
        'reinforce',
        focusConstraints, // Same weak skill targeting as focus slots
        type,
        config,
        costCalculator,
        studentMaxSkillCost,
        comfortLevel,
        comfortFactors,
        comfortAdjustment,
        rawComfortLevel,
        termCountScalingConfig
      )
    )
  }

  // Review slots: spaced repetition of mastered skills
  for (let i = 0; i < reviewCount; i++) {
    const skill = needsReview[i % Math.max(1, needsReview.length)]
    slots.push(
      createSlot(
        slots.length,
        'review',
        skill ? buildConstraintsForSkill(skill, phaseConstraints) : phaseConstraints,
        type,
        config,
        costCalculator,
        studentMaxSkillCost,
        comfortLevel,
        comfortFactors,
        comfortAdjustment,
        rawComfortLevel,
        termCountScalingConfig
      )
    )
  }

  // Challenge slots: use same mastered skills constraints (all problems should use student's skills)
  for (let i = 0; i < challengeCount; i++) {
    slots.push(
      createSlot(
        slots.length,
        'challenge',
        phaseConstraints,
        type,
        config,
        costCalculator,
        studentMaxSkillCost,
        comfortLevel,
        comfortFactors,
        comfortAdjustment,
        rawComfortLevel,
        termCountScalingConfig
      )
    )
  }

  // Optionally shuffle to interleave purposes (default: shuffled)
  const shuffledSlots = shufflePurposes ? intelligentShuffle(slots) : slots

  // Generate problems for each slot (persisted in DB for resume capability)
  const slotsWithProblems = shuffledSlots.map((slot) => ({
    ...slot,
    problem: generateProblemFromConstraints(slot.constraints, costCalculator),
  }))

  return {
    partNumber,
    type,
    format: type === 'linear' ? 'linear' : 'vertical',
    useAbacus: type === 'abacus',
    slots: slotsWithProblems,
    estimatedMinutes: Math.round(partDurationMinutes),
  }
}
 
/**
 * Async version of buildSessionPart that yields the event loop periodically
 * to allow Socket.IO broadcasts to flush during problem generation.
 */
async function buildSessionPartAsync(
  partNumber: 1 | 2 | 3,
  type: SessionPartType,
  totalDurationMinutes: number,
  avgTimeSeconds: number,
  config: PlanGenerationConfig,
  phaseConstraints: ReturnType<typeof getPhaseSkillConstraints>,
  needsReview: PlayerSkillMastery[],
  currentPhase: CurriculumPhase | undefined,
  normalizedWeight?: number,
  costCalculator?: SkillCostCalculator,
  studentMaxSkillCost?: number,
  weakSkills?: string[],
  overrideProblemsPerPart?: number,
  shufflePurposes = true,
  comfortLevel = 0.3,
  comfortFactors?: TermCountExplanation['factors'],
  comfortAdjustment?: number,
  rawComfortLevel?: number,
  termCountScalingConfig?: TermCountScalingConfig,
  onProblemGenerated?: (current: number, total: number) => void
): Promise<SessionPart> {
  // Get time allocation for this part (use normalized weight if provided)
  const partWeight = normalizedWeight ?? config.partTimeWeights[type]
  const partDurationMinutes = totalDurationMinutes * partWeight
  const partProblemCount =
    overrideProblemsPerPart ?? Math.max(2, Math.floor((partDurationMinutes * 60) / avgTimeSeconds))

  const challengeMinBudget = config.purposeComplexityBounds.challenge[type].min ?? 0
  const canDoChallenge =
    studentMaxSkillCost !== undefined && studentMaxSkillCost >= challengeMinBudget

  const weights = {
    focus: config.focusWeight,
    reinforce: config.reinforceWeight,
    review: config.reviewWeight,
    challenge: canDoChallenge ? (config.challengeWeight ?? 0.2) : 0,
  }
  const totalWeight = weights.focus + weights.reinforce + weights.review + weights.challenge

  const focusCount = Math.round((partProblemCount * weights.focus) / totalWeight)
  const reinforceCount = Math.round((partProblemCount * weights.reinforce) / totalWeight)
  const reviewCount = Math.round((partProblemCount * weights.review) / totalWeight)
  const challengeCount = canDoChallenge
    ? Math.max(0, partProblemCount - focusCount - reinforceCount - reviewCount)
    : 0
  const adjustedFocusCount =
    focusCount + (canDoChallenge ? 0 : partProblemCount - focusCount - reinforceCount - reviewCount)

  const slots: ProblemSlot[] = []

  const focusConstraints =
    weakSkills && weakSkills.length > 0
      ? addWeakSkillsToTargets(phaseConstraints, weakSkills)
      : phaseConstraints

  for (let i = 0; i < adjustedFocusCount; i++) {
    slots.push(
      createSlot(
        slots.length,
        'focus',
        focusConstraints,
        type,
        config,
        costCalculator,
        studentMaxSkillCost,
        comfortLevel,
        comfortFactors,
        comfortAdjustment,
        rawComfortLevel,
        termCountScalingConfig
      )
    )
  }
  for (let i = 0; i < reinforceCount; i++) {
    slots.push(
      createSlot(
        slots.length,
        'reinforce',
        focusConstraints,
        type,
        config,
        costCalculator,
        studentMaxSkillCost,
        comfortLevel,
        comfortFactors,
        comfortAdjustment,
        rawComfortLevel,
        termCountScalingConfig
      )
    )
  }
  for (let i = 0; i < reviewCount; i++) {
    const skill = needsReview[i % Math.max(1, needsReview.length)]
    slots.push(
      createSlot(
        slots.length,
        'review',
        skill ? buildConstraintsForSkill(skill, phaseConstraints) : phaseConstraints,
        type,
        config,
        costCalculator,
        studentMaxSkillCost,
        comfortLevel,
        comfortFactors,
        comfortAdjustment,
        rawComfortLevel,
        termCountScalingConfig
      )
    )
  }
  for (let i = 0; i < challengeCount; i++) {
    slots.push(
      createSlot(
        slots.length,
        'challenge',
        phaseConstraints,
        type,
        config,
        costCalculator,
        studentMaxSkillCost,
        comfortLevel,
        comfortFactors,
        comfortAdjustment,
        rawComfortLevel,
        termCountScalingConfig
      )
    )
  }

  const shuffledSlots = shufflePurposes ? intelligentShuffle(slots) : slots

  // Generate problems with async yielding for Socket.IO broadcast flushing
  const slotsWithProblems: ProblemSlot[] = []
  for (let i = 0; i < shuffledSlots.length; i++) {
    const slot = shuffledSlots[i]
    slotsWithProblems.push({
      ...slot,
      problem: generateProblemFromConstraints(slot.constraints, costCalculator),
    })
    onProblemGenerated?.(i + 1, shuffledSlots.length)

    // Yield event loop every 3 problems to allow Socket.IO broadcasts to flush
    if (onProblemGenerated && (i + 1) % 3 === 0 && i < shuffledSlots.length - 1) {
      await new Promise<void>((r) => setTimeout(r, 0))
    }
  }

  return {
    partNumber,
    type,
    format: type === 'linear' ? 'linear' : 'vertical',
    useAbacus: type === 'abacus',
    slots: slotsWithProblems,
    estimatedMinutes: Math.round(partDurationMinutes),
  }
}
 
// ============================================================================
// Plan Management
// ============================================================================
 
/**
 * Get a session plan by ID
 */
export async function getSessionPlan(planId: string): Promise<SessionPlan | null> {
  const result = await db.query.sessionPlans.findFirst({
    where: eq(schema.sessionPlans.id, planId),
  })
  return result ?? null
}
 
/**
 * Check if a session plan has pre-generated problems for all slots
 * Old sessions created before problem pre-generation was added will fail this check
 */
function sessionHasPreGeneratedProblems(plan: SessionPlan): boolean {
  for (const part of plan.parts) {
    for (const slot of part.slots) {
      if (!slot.problem) {
        return false
      }
    }
  }
  return true
}
 
/**
 * Get active session plan for a player (in_progress status)
 * Returns the most recent in_progress session if multiple exist
 * Auto-abandons sessions that are missing pre-generated problems (legacy data)
 */
export async function getActiveSessionPlan(playerId: string): Promise<SessionPlan | null> {
  // Find any session that's not completed or abandoned
  // This includes: draft, approved, in_progress
  // IMPORTANT: Also check completedAt IS NULL to handle inconsistent data
  // where status may be in_progress but completedAt is set
  const result = await db.query.sessionPlans.findFirst({
    where: and(
      eq(schema.sessionPlans.playerId, playerId),
      inArray(schema.sessionPlans.status, ['draft', 'approved', 'in_progress']),
      isNull(schema.sessionPlans.completedAt)
    ),
    orderBy: (plans, { desc }) => [desc(plans.createdAt)],
  })

  if (!result) {
    return null
  }

  // Validate session has pre-generated problems
  // Old sessions may not have them - auto-abandon those
  if (!sessionHasPreGeneratedProblems(result)) {
    console.warn(
      `[getActiveSessionPlan] Session ${result.id} missing pre-generated problems, auto-abandoning`
    )
    await abandonSessionPlan(result.id)
    // Recursively check for another active session
    return getActiveSessionPlan(playerId)
  }

  return result
}
 
/**
 * Get the most recently completed session plan for a player
 * Used for the summary page after completing a session
 */
export async function getMostRecentCompletedSession(playerId: string): Promise<SessionPlan | null> {
  const result = await db.query.sessionPlans.findFirst({
    where: and(
      eq(schema.sessionPlans.playerId, playerId),
      eq(schema.sessionPlans.status, 'completed')
    ),
    orderBy: (plans, { desc }) => [desc(plans.completedAt)],
  })
  return result ?? null
}
 
/**
 * Result from a problem with session context for traceability
 */
export interface ProblemResultWithContext extends SlotResult {
  /** Session ID this result came from */
  sessionId: string
  /** When the session was completed */
  sessionCompletedAt: Date
  /** Part type (abacus/visualization/linear) */
  partType: SessionPartType
}
 
/**
 * Get recent problem results across multiple sessions for skills analysis
 *
 * Returns a flat list of problem results with session context,
 * ordered by most recent first.
 *
 * @param playerId - The player to fetch results for
 * @param sessionCount - Number of recent sessions to include (default 50)
 */
export async function getRecentSessionResults(
  playerId: string,
  sessionCount = 50
): Promise<ProblemResultWithContext[]> {
  const map = await batchGetRecentSessionResults([playerId], sessionCount)
  return map.get(playerId) ?? []
}
 
/**
 * Batch-fetch recent problem results for multiple players in a single query.
 *
 * Returns a Map<playerId, ProblemResultWithContext[]> with results ordered
 * by timestamp descending (most recent first).
 *
 * @param playerIds - The players to fetch results for
 * @param sessionCountPerPlayer - Max sessions per player (default 50)
 */
export async function batchGetRecentSessionResults(
  playerIds: string[],
  sessionCountPerPlayer = 50
): Promise<Map<string, ProblemResultWithContext[]>> {
  const resultMap = new Map<string, ProblemResultWithContext[]>()
  if (playerIds.length === 0) return resultMap
 
  // Include both 'completed' sessions and 'recency-refresh' sentinels
  // Recency-refresh sessions contain sentinel records that update lastPracticedAt
  // but are zero-weight for BKT mastery calculation
  //
  // Use .select() instead of .findMany() to skip the massive `parts` column
  // (which contains full problem generation traces, 10-50KB per session).
  // Instead, extract just the partNumber→type mapping via a SQLite JSON subquery.
  const sessions = await db
    .select({
      id: schema.sessionPlans.id,
      playerId: schema.sessionPlans.playerId,
      completedAt: schema.sessionPlans.completedAt,
      results: schema.sessionPlans.results,
      // Extract lightweight [{n: partNumber, t: type}, ...] from parts JSON
      // instead of fetching the entire parts column with all slots/problems
      partTypeMap: sql<string>`(
        SELECT json_group_array(json_object(
          'n', json_extract(value, '$.partNumber'),
          't', json_extract(value, '$.type')
        )) FROM json_each(${schema.sessionPlans.parts})
      )`,
    })
    .from(schema.sessionPlans)
    .where(
      and(
        inArray(schema.sessionPlans.playerId, playerIds),
        inArray(schema.sessionPlans.status, ['completed', 'recency-refresh'])
      )
    )
    .orderBy(desc(schema.sessionPlans.completedAt))
 
  // Cap sessions per player and flatten results with session context
  const sessionCountByPlayer = new Map<string, number>()
 
  for (const session of sessions) {
    if (!session.completedAt) continue
 
    const count = sessionCountByPlayer.get(session.playerId) ?? 0
    if (count >= sessionCountPerPlayer) continue
    sessionCountByPlayer.set(session.playerId, count + 1)
 
    let list = resultMap.get(session.playerId)
    if (!list) {
      list = []
      resultMap.set(session.playerId, list)
    }
 
    // Build partNumber→type lookup from the lightweight extraction
    const partTypes = JSON.parse(session.partTypeMap || '[]') as Array<{ n: number; t: string }>
    const typeByPartNumber = new Map(partTypes.map((p) => [p.n, p.t]))
 
    for (const result of session.results) {
      // Some pre-schema fixtures (e.g. validation seed plans) carry result
      // entries that don't match SlotResult — missing skillsExercised,
      // partNumber, etc. Skip them so downstream consumers can assume the
      // SlotResult contract holds. Real practice records always have at
      // least `skillsExercised: []` from `recordSlotResult`.
      if (!Array.isArray((result as Partial<SlotResult>).skillsExercised)) continue
 
      const partType = (typeByPartNumber.get(result.partNumber) ?? 'linear') as SessionPartType
 
      list.push({
        ...result,
        sessionId: session.id,
        sessionCompletedAt: session.completedAt,
        partType,
      })
    }
  }
 
  // Sort each player's results by timestamp descending (most recent first)
  for (const list of resultMap.values()) {
    list.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
  }
 
  return resultMap
}
 
/**
 * Approve a plan (teacher says "Let's Go!")
 */
export async function approveSessionPlan(planId: string): Promise<SessionPlan> {
  const now = new Date()
  const [updated] = await db
    .update(schema.sessionPlans)
    .set({
      status: 'approved',
      approvedAt: now,
    })
    .where(eq(schema.sessionPlans.id, planId))
    .returning()
  return updated
}
 
/**
 * Start a session (first problem displayed)
 */
export async function startSessionPlan(planId: string): Promise<SessionPlan> {
  const now = new Date()
  const initialHealth: SessionHealth = {
    overall: 'good',
    accuracy: 1,
    pacePercent: 100,
    currentStreak: 0,
    avgResponseTimeMs: 0,
  }

  const [updated] = await db
    .update(schema.sessionPlans)
    .set({
      status: 'in_progress',
      flowState: 'practicing',
      flowUpdatedAt: now,
      flowVersion: sql`${schema.sessionPlans.flowVersion} + 1`,
      startedAt: now,
      sessionHealth: initialHealth,
    })
    .where(eq(schema.sessionPlans.id, planId))
    .returning()
  return updated
}
 
/**
 * Record a result for a slot and advance to next
 */
export async function recordSlotResult(
  planId: string,
  result: Omit<
    SlotResult,
    'timestamp' | 'partNumber' | 'epochNumber' | 'masteryWeight' | 'isRetry' | 'originalSlotIndex'
  >
): Promise<SessionPlan> {
  const traceStart = Date.now()
  let plan: SessionPlan | null
  try {
    plan = await getSessionPlan(planId)
  } catch (error) {
    console.error(`[recordSlotResult] Failed to get plan ${planId}:`, error)
    throw new Error(
      `Failed to retrieve plan ${planId}: ${error instanceof Error ? error.message : String(error)}`
    )
  }

  if (!plan) throw new Error(`Plan not found: ${planId}`)

  // Defensive check: ensure parts array exists and is valid
  if (!plan.parts || !Array.isArray(plan.parts)) {
    throw new Error(
      `Plan ${planId} has invalid parts: ${typeof plan.parts} (status: ${plan.status}, partIndex: ${plan.currentPartIndex})`
    )
  }

  if (plan.parts.length === 0) {
    throw new Error(`Plan ${planId} has empty parts array`)
  }

  if (plan.currentPartIndex < 0 || plan.currentPartIndex >= plan.parts.length) {
    throw new Error(
      `Plan ${planId} has invalid currentPartIndex: ${plan.currentPartIndex} (parts.length: ${plan.parts.length})`
    )
  }

  const currentPart = plan.parts[plan.currentPartIndex]
  if (!currentPart) throw new Error(`Invalid part index: ${plan.currentPartIndex}`)

  console.log('[GBTRACE][server]', 'record-slot-result-start', {
    ts: new Date().toISOString(),
    planId,
    playerId: plan.playerId,
    currentPartIndex: plan.currentPartIndex,
    currentSlotIndex: plan.currentSlotIndex,
    currentPartNumber: currentPart.partNumber,
    currentPartType: currentPart.type,
    submittedSlotIndex: result.slotIndex,
    isCorrect: result.isCorrect,
  })

  // Defensive check: ensure slots array exists
  if (!currentPart.slots || !Array.isArray(currentPart.slots)) {
    throw new Error(
      `Plan ${planId} part ${plan.currentPartIndex} has invalid slots: ${typeof currentPart.slots}`
    )
  }

  // Defensive check: ensure results array exists
  if (!plan.results || !Array.isArray(plan.results)) {
    throw new Error(`Plan ${planId} has invalid results: ${typeof plan.results} (expected array)`)
  }

  // Initialize mutable copy of retry state
  const updatedRetryState: SessionRetryState = plan.retryState ? { ...plan.retryState } : {}
  const partIndex = plan.currentPartIndex

  // Determine if we're in a retry epoch or working original slots
  const inRetryEpoch = isInRetryEpoch(plan, partIndex)
  let epochNumber = 0
  let originalSlotIndex = result.slotIndex

  if (inRetryEpoch) {
    // In retry epoch
    const retryState = updatedRetryState[partIndex]!
    const currentRetryItem = retryState.currentEpochItems[retryState.currentRetryIndex]
    epochNumber = currentRetryItem.epochNumber
    originalSlotIndex = currentRetryItem.originalSlotIndex
  }

  // Calculate mastery weight based on epoch and correctness
  const masteryWeight = calculateMasteryWeight(result.isCorrect, epochNumber)

  const newResult: SlotResult = {
    ...result,
    partNumber: currentPart.partNumber,
    timestamp: new Date(),
    epochNumber,
    masteryWeight,
    isRetry: epochNumber > 0,
    originalSlotIndex,
  }

  const updatedResults = [...plan.results, newResult]

  // Handle wrong answers: queue for retry
  if (!result.isCorrect) {
    if (inRetryEpoch) {
      // In retry epoch - queue for next epoch if under max
      const retryState = updatedRetryState[partIndex]!
      if (retryState.currentEpoch < MAX_RETRY_EPOCHS) {
        const currentRetryItem = retryState.currentEpochItems[retryState.currentRetryIndex]
        retryState.pendingRetries.push({
          slotId: currentRetryItem.slotId,
          originalSlotIndex: currentRetryItem.originalSlotIndex,
          problem: currentRetryItem.problem,
          epochNumber: retryState.currentEpoch + 1,
          originalPurpose: currentRetryItem.originalPurpose,
        })
      }
      // If at max epoch, don't re-queue (counted as definitively wrong)
    } else {
      // Original attempt wrong - queue for first retry epoch
      const retryState = initRetryState({ ...plan, retryState: updatedRetryState }, partIndex)
      updatedRetryState[partIndex] = retryState
      const slot = currentPart.slots[plan.currentSlotIndex]
      retryState.pendingRetries.push({
        slotId: slot.slotId,
        originalSlotIndex: plan.currentSlotIndex,
        problem: slot.problem!,
        epochNumber: 1,
        originalPurpose: slot.purpose,
      })
    }
  }

  // Advance to next problem
  let nextPartIndex = plan.currentPartIndex
  let nextSlotIndex = plan.currentSlotIndex
  let isComplete = false

  if (inRetryEpoch) {
    // Advance within retry epoch
    const retryState = updatedRetryState[partIndex]!
    retryState.currentRetryIndex += 1

    if (retryState.currentRetryIndex >= retryState.currentEpochItems.length) {
      // Finished current retry epoch
      if (retryState.pendingRetries.length > 0 && retryState.currentEpoch < MAX_RETRY_EPOCHS) {
        // Start next retry epoch
        retryState.currentEpoch += 1
        retryState.currentEpochItems = [...retryState.pendingRetries]
        retryState.pendingRetries = []
        retryState.currentRetryIndex = 0
      } else {
        // No more retries (either all correct or max epochs reached)
        // Clear retry state and advance to next part
        retryState.currentEpochItems = []
        retryState.currentRetryIndex = 0
        retryState.pendingRetries = []
        nextPartIndex += 1
        nextSlotIndex = 0

        if (nextPartIndex >= plan.parts.length) {
          isComplete = true
        }
      }
    }
  } else {
    // Advance within original slots
    nextSlotIndex += 1

    if (nextSlotIndex >= currentPart.slots.length) {
      // Finished original slots for this part
      const retryState = updatedRetryState[partIndex]

      if (retryState && retryState.pendingRetries.length > 0) {
        // Start retry epoch 1
        retryState.currentEpoch = 1
        retryState.currentEpochItems = [...retryState.pendingRetries]
        retryState.pendingRetries = []
        retryState.currentRetryIndex = 0
        // Stay on same part, slot index stays at end (indicates original slots done)
      } else {
        // No retries needed, advance to next part
        nextPartIndex += 1
        nextSlotIndex = 0

        if (nextPartIndex >= plan.parts.length) {
          isComplete = true
        }
      }
    }
  }

  // Calculate elapsed time since start
  const elapsedMs = plan.startedAt ? Date.now() - plan.startedAt.getTime() : 0
  const updatedHealth = calculateSessionHealth({ ...plan, results: updatedResults }, elapsedMs)
  const partTransitioned = nextPartIndex > plan.currentPartIndex
  const hasMoreParts = nextPartIndex < plan.parts.length
  const gameBreakEnabled = (plan.gameBreakSettings as GameBreakSettings | null)?.enabled ?? false

  let dbResult
  try {
    const nextFlowState: SessionFlowState = isComplete
      ? 'completed'
      : partTransitioned && hasMoreParts && gameBreakEnabled
        ? 'part_transition'
        : 'practicing'
    const flowUpdatedAt = new Date()
    const flowStateChanged =
      (plan.flowState ?? 'practicing') !== nextFlowState ||
      plan.breakStartedAt !== null ||
      plan.breakResults !== null
    const nextFlowVersion = (plan.flowVersion ?? 0) + (flowStateChanged ? 1 : 0)
    dbResult = await db
      .update(schema.sessionPlans)
      .set({
        results: updatedResults,
        currentPartIndex: nextPartIndex,
        currentSlotIndex: nextSlotIndex,
        sessionHealth: updatedHealth,
        retryState: updatedRetryState,
        status: isComplete ? 'completed' : 'in_progress',
        flowState: nextFlowState,
        flowUpdatedAt: flowStateChanged ? flowUpdatedAt : (plan.flowUpdatedAt ?? flowUpdatedAt),
        flowVersion: nextFlowVersion,
        // Clear operational break fields but preserve metadata (breakSelectedGame,
        // breakReason) — the song generator needs them later in the session.
        breakStartedAt: null,
        breakResults: null,
        completedAt: isComplete ? new Date() : null,
      })
      .where(eq(schema.sessionPlans.id, planId))
      .returning()
  } catch (dbError) {
    console.error(`[recordSlotResult] Drizzle update FAILED:`, dbError)
    throw dbError
  }

  const [updated] = dbResult

  // Defensive check: ensure update succeeded
  if (!updated) {
    throw new Error(
      `Failed to update plan ${planId}: no rows returned (may have been deleted during update)`
    )
  }

  // Update global skill mastery timestamps with help tracking
  // Note: masteryWeight is applied by BKT when it reads SlotResults (not here)
  if (result.skillsExercised && result.skillsExercised.length > 0) {
    const skillResults = result.skillsExercised.map((skillId) => ({
      skillId,
      isCorrect: result.isCorrect,
    }))
    try {
      await recordSkillAttemptsWithHelp(
        plan.playerId,
        skillResults,
        result.hadHelp,
        result.responseTimeMs
      )
    } catch (skillError) {
      console.error(`[recordSlotResult] recordSkillAttemptsWithHelp FAILED:`, skillError)
      throw skillError
    }
  }

  // Revoke any active share links when session completes
  if (isComplete) {
    try {
      await revokeSharesForSession(planId)
    } catch (shareError) {
      // Non-critical: log and continue (session already completed successfully)
      console.error(`[recordSlotResult] revokeSharesForSession FAILED:`, shareError)
    }
  }

  console.log('[GBTRACE][server]', 'record-slot-result-finish', {
    ts: new Date().toISOString(),
    planId,
    playerId: plan.playerId,
    durationMs: Date.now() - traceStart,
    previousPartIndex: plan.currentPartIndex,
    previousSlotIndex: plan.currentSlotIndex,
    nextPartIndex,
    nextSlotIndex,
    partTransitioned,
    hasMoreParts,
    gameBreakEnabled,
    inRetryEpoch,
    isComplete,
    status: updated.status,
  })

  return updated
}
 
/**
 * Context for a manual redo operation
 */
export interface RedoContext {
  /** Part index of the problem being redone */
  originalPartIndex: number
  /** Slot index of the problem being redone */
  originalSlotIndex: number
  /** Whether the original answer was correct (affects recording logic) */
  originalWasCorrect: boolean
}
 
/**
 * Record a result from a manual redo (student tapped a completed problem to redo it).
 *
 * Key differences from recordSlotResult:
 * - Does NOT advance currentPartIndex/currentSlotIndex (session position unchanged)
 * - If original was wrong and redo is correct: removes from retry queue (redeems)
 * - Result is marked with isManualRedo: true
 */
export async function recordRedoResult(
  planId: string,
  result: Omit<SlotResult, 'timestamp' | 'partNumber'>,
  redoContext: RedoContext
): Promise<SessionPlan> {
  const plan = await getSessionPlan(planId)
  if (!plan) throw new Error(`Plan not found: ${planId}`)

  // Validate part index
  if (redoContext.originalPartIndex < 0 || redoContext.originalPartIndex >= plan.parts.length) {
    throw new Error(`Invalid part index: ${redoContext.originalPartIndex}`)
  }

  const part = plan.parts[redoContext.originalPartIndex]

  // Reject redo if the answer was already divulged (student exhausted all retries wrong)
  const answerWasDivulged = (plan.results || []).some(
    (r) =>
      r.partNumber === part.partNumber &&
      (r.originalSlotIndex ?? r.slotIndex) === redoContext.originalSlotIndex &&
      !r.isCorrect &&
      !r.isManualRedo &&
      (r.epochNumber ?? 0) >= MAX_RETRY_EPOCHS
  )
  if (answerWasDivulged) {
    throw new Error(
      `Cannot redo slot ${redoContext.originalSlotIndex} in part ${redoContext.originalPartIndex}: answer was already revealed after exhausting retries`
    )
  }

  // Build the result with manual redo flag
  const newResult: SlotResult = {
    ...result,
    partNumber: part.partNumber,
    timestamp: new Date(),
    isManualRedo: true,
    // For manual redos, we use epoch 0 and no retry flags since this is user-initiated
    epochNumber: 0,
    masteryWeight: result.isCorrect ? 1.0 : 0,
    isRetry: false,
    originalSlotIndex: redoContext.originalSlotIndex,
  }

  const updatedResults = [...(plan.results || []), newResult]

  // Handle retry queue updates if original was wrong and redo is correct
  const updatedRetryState = plan.retryState ? { ...plan.retryState } : {}

  if (!redoContext.originalWasCorrect && result.isCorrect) {
    // Original was wrong, redo is correct - redeem from retry queue
    const partRetryState = updatedRetryState[redoContext.originalPartIndex]

    if (partRetryState) {
      // Remove from pendingRetries (if not yet in active epoch)
      partRetryState.pendingRetries = partRetryState.pendingRetries.filter(
        (item) => item.originalSlotIndex !== redoContext.originalSlotIndex
      )

      // Add to redeemedSlots (for skipping in currentEpochItems)
      partRetryState.redeemedSlots = partRetryState.redeemedSlots || []
      if (!partRetryState.redeemedSlots.includes(redoContext.originalSlotIndex)) {
        partRetryState.redeemedSlots.push(redoContext.originalSlotIndex)
      }

      updatedRetryState[redoContext.originalPartIndex] = partRetryState
    }
  }

  // Calculate updated health (redo results affect accuracy)
  const elapsedMs = plan.startedAt ? Date.now() - plan.startedAt.getTime() : 0
  const updatedHealth = calculateSessionHealth({ ...plan, results: updatedResults }, elapsedMs)

  // Update database - note: currentPartIndex/currentSlotIndex are NOT modified
  const [updated] = await db
    .update(schema.sessionPlans)
    .set({
      results: updatedResults,
      sessionHealth: updatedHealth,
      retryState: updatedRetryState,
    })
    .where(eq(schema.sessionPlans.id, planId))
    .returning()

  if (!updated) {
    throw new Error(`Failed to update plan ${planId}: no rows returned`)
  }

  // Update global skill mastery timestamps
  if (result.skillsExercised && result.skillsExercised.length > 0) {
    const skillResults = result.skillsExercised.map((skillId) => ({
      skillId,
      isCorrect: result.isCorrect,
    }))
    try {
      await recordSkillAttemptsWithHelp(
        plan.playerId,
        skillResults,
        result.hadHelp ?? false,
        result.responseTimeMs
      )
    } catch (skillError) {
      console.error(`[recordRedoResult] recordSkillAttemptsWithHelp FAILED:`, skillError)
      // Don't throw - redo result was already recorded
    }
  }

  return updated
}
 
export class StaleFlowVersionError extends Error {
  constructor(
    public readonly expectedFlowVersion: number,
    public readonly actualFlowVersion: number
  ) {
    super(
      `Stale flow event: expected flowVersion ${expectedFlowVersion}, actual ${actualFlowVersion}`
    )
    this.name = 'StaleFlowVersionError'
  }
}
 
export async function applySessionFlowEvent(
  planId: string,
  event: SessionFlowEvent,
  expectedFlowVersion?: number
): Promise<SessionPlan> {
  const plan = await getSessionPlan(planId)
  if (!plan) throw new Error(`Plan not found: ${planId}`)

  if (
    expectedFlowVersion !== undefined &&
    expectedFlowVersion !== null &&
    expectedFlowVersion !== (plan.flowVersion ?? 0)
  ) {
    const postCheck = applyFlowEvent(plan, event)
    if (!postCheck.changed) return plan
    throw new StaleFlowVersionError(expectedFlowVersion, plan.flowVersion ?? 0)
  }

  const applied = applyFlowEvent(plan, event)
  if (!applied.changed) return plan

  const currentFlowVersion = plan.flowVersion ?? 0
  const [updated] = await db
    .update(schema.sessionPlans)
    .set(applied.patch)
    .where(
      and(
        eq(schema.sessionPlans.id, planId),
        eq(schema.sessionPlans.flowVersion, currentFlowVersion)
      )
    )
    .returning()

  if (updated) return updated

  const latestPlan = await getSessionPlan(planId)
  if (!latestPlan) throw new Error(`Plan not found after flow update: ${planId}`)
  const replay = applyFlowEvent(latestPlan, event)
  if (!replay.changed) return latestPlan

  throw new StaleFlowVersionError(currentFlowVersion, latestPlan.flowVersion ?? 0)
}
 
/**
 * Complete a session early (teacher ends it)
 */
export async function completeSessionPlanEarly(
  planId: string,
  reason?: string
): Promise<SessionPlan> {
  const plan = await getSessionPlan(planId)
  if (!plan) throw new Error(`Plan not found: ${planId}`)

  const adjustment = {
    timestamp: new Date(),
    type: 'ended_early' as const,
    reason,
    previousHealth: plan.sessionHealth || {
      overall: 'good' as const,
      accuracy: 1,
      pacePercent: 100,
      currentStreak: 0,
      avgResponseTimeMs: 0,
    },
  }

  const flowPlan = await applySessionFlowEvent(planId, { type: 'SESSION_COMPLETED' })

  const [updated] = await db
    .update(schema.sessionPlans)
    .set({
      status: 'completed',
      flowState: flowPlan.flowState,
      flowUpdatedAt: flowPlan.flowUpdatedAt,
      flowVersion: flowPlan.flowVersion,
      completedAt: new Date(),
      adjustments: [...plan.adjustments, adjustment],
    })
    .where(eq(schema.sessionPlans.id, planId))
    .returning()

  // Revoke any active share links
  try {
    await revokeSharesForSession(planId)
  } catch (shareError) {
    console.error(`[completeSessionPlanEarly] revokeSharesForSession FAILED:`, shareError)
  }

  return updated
}
 
/**
 * Abandon a session (user navigates away, closes browser, etc.)
 */
export async function abandonSessionPlan(planId: string): Promise<SessionPlan> {
  const flowPlan = await applySessionFlowEvent(planId, { type: 'SESSION_ABANDONED' })
  const [updated] = await db
    .update(schema.sessionPlans)
    .set({
      status: 'abandoned',
      flowState: flowPlan.flowState,
      flowUpdatedAt: flowPlan.flowUpdatedAt,
      flowVersion: flowPlan.flowVersion,
      completedAt: new Date(),
    })
    .where(eq(schema.sessionPlans.id, planId))
    .returning()

  // Revoke any active share links
  try {
    await revokeSharesForSession(planId)
  } catch (shareError) {
    console.error(`[abandonSessionPlan] revokeSharesForSession FAILED:`, shareError)
  }

  return updated
}
 
export async function completePartTransition(planId: string): Promise<SessionPlan> {
  const plan = await getSessionPlan(planId)
  if (!plan) throw new Error(`Plan not found: ${planId}`)

  const gameBreakEnabled = (plan.gameBreakSettings as GameBreakSettings | null)?.enabled ?? false
  const hasMoreParts = plan.currentPartIndex < plan.parts.length
  const shouldOpenBreak = gameBreakEnabled && hasMoreParts
  return applySessionFlowEvent(planId, {
    type: 'PART_TRANSITION_COMPLETED',
    shouldRunBreak: shouldOpenBreak,
  })
}
 
export async function finishGameBreak(
  planId: string,
  reason: 'timeout' | 'gameFinished' | 'skipped',
  results?: GameResultsReport | null
): Promise<SessionPlan> {
  return applySessionFlowEvent(planId, {
    type: 'BREAK_FINISHED',
    reason,
    results,
  })
}
 
export async function acknowledgeGameBreakResults(planId: string): Promise<SessionPlan> {
  return applySessionFlowEvent(planId, { type: 'BREAK_RESULTS_ACKED' })
}
 
/**
 * Update session plan results directly.
 * Used for teacher/parent edits (mark correct, exclude, etc.)
 */
export async function updateSessionPlanResults(
  planId: string,
  results: SlotResult[]
): Promise<SessionPlan> {
  // Get the current plan to recalculate health
  const plan = await getSessionPlan(planId)
  if (!plan) {
    throw new Error(`Plan ${planId} not found`)
  }

  // Create a temporary plan with updated results to calculate health
  const tempPlan = { ...plan, results }

  // Calculate elapsed time since session started
  const startedAt = plan.startedAt instanceof Date ? plan.startedAt : new Date(plan.startedAt ?? 0)
  const elapsedTimeMs = Date.now() - startedAt.getTime()

  const newHealth = calculateSessionHealth(tempPlan, elapsedTimeMs)

  const [updated] = await db
    .update(schema.sessionPlans)
    .set({
      results,
      sessionHealth: newHealth,
    })
    .where(eq(schema.sessionPlans.id, planId))
    .returning()

  return updated
}
 
/**
 * Update the remote camera session ID for a session plan.
 * Used when setting up phone camera for vision-based practice.
 */
export async function updateSessionPlanRemoteCamera(
  planId: string,
  remoteCameraSessionId: string | null
): Promise<SessionPlan> {
  const [updated] = await db
    .update(schema.sessionPlans)
    .set({ remoteCameraSessionId })
    .where(eq(schema.sessionPlans.id, planId))
    .returning()

  if (!updated) {
    throw new Error(`Plan ${planId} not found`)
  }

  return updated
}
 
// ============================================================================
// Helper Functions
// ============================================================================
 
/**
 * Identify weak skills from BKT estimates.
 *
 * A skill is considered "weak" when BKT confidently estimates a low P(known).
 * These skills should be prioritized in practice to help the student improve.
 *
 * @param bktResults - BKT results keyed by skillId
 * @returns Array of skillIds that are weak and should be prioritized
 */
function identifyWeakSkills(bktResults: Map<string, SkillBktResult> | undefined): string[] {
  if (!bktResults) return []

  const weakSkills: string[] = []
  const { confidenceThreshold, pKnownThreshold } = WEAK_SKILL_THRESHOLDS

  for (const [skillId, result] of bktResults) {
    // Weak = confident that P(known) is low
    if (result.confidence >= confidenceThreshold && result.pKnown < pKnownThreshold) {
      weakSkills.push(skillId)
    }
  }

  return weakSkills
}
 
/**
 * Get term count constraints based on part type, comfort level, and config overrides.
 *
 * Uses dynamic comfort-based scaling, with config overrides acting as ceiling.
 *
 * @param partType - The session part type
 * @param config - Plan generation config (contains parent/teacher overrides)
 * @param comfortLevel - Student comfort level (0-1)
 * @param comfortFactors - Individual factors that produced the comfort level
 * @returns The final range and an explanation for UI display
 */
function getTermCountForPartType(
  partType: SessionPartType,
  config: PlanGenerationConfig,
  comfortLevel: number,
  comfortFactors?: TermCountExplanation['factors'],
  comfortAdjustment?: number,
  rawComfortLevel?: number,
  termCountScalingConfig?: TermCountScalingConfig
): { range: { min: number; max: number }; explanation: TermCountExplanation } {
  const dynamicRange = computeTermCountRange(partType, comfortLevel, termCountScalingConfig)

  // Get config override for this part type (parent/teacher setting)
  const override =
    partType === 'abacus'
      ? config.abacusTermCount
      : partType === 'visualization'
        ? config.visualizationTermCount
        : config.linearTermCount

  const finalRange = applyTermCountOverride(dynamicRange, override)

  const factors = comfortFactors ?? {
    avgMastery: null,
    sessionMode: 'maintenance',
    modeMultiplier: 1.0,
    skillCountBonus: 0,
  }

  return {
    range: finalRange,
    explanation: {
      comfortLevel,
      factors,
      dynamicRange,
      override: override ?? null,
      finalRange,
      ...(comfortAdjustment !== undefined && comfortAdjustment !== 0
        ? { comfortAdjustment, rawComfortLevel }
        : {}),
    },
  }
}
 
/**
 * Get complexity bounds (min/max) for a specific purpose and part type.
 *
 * For visualization mode, the max budget is dynamically calculated to ensure
 * the student's current learning skills can appear. This prevents the static
 * max from blocking skills the student is supposed to be practicing.
 *
 * @param purpose - The slot purpose (focus, reinforce, review, challenge)
 * @param partType - The part type (abacus, visualization, linear)
 * @param config - Plan generation config with default bounds
 * @param studentMaxSkillCost - The max effective cost for any skill the student has
 *                              (includes mastery multiplier). Used to set dynamic
 *                              visualization budget.
 */
function getComplexityBoundsForSlot(
  purpose: ProblemSlot['purpose'],
  partType: SessionPartType,
  config: PlanGenerationConfig,
  studentMaxSkillCost?: number
): { min?: number; max?: number } {
  const purposeBounds = config.purposeComplexityBounds?.[purpose]
  if (!purposeBounds) {
    return {}
  }

  const partBounds = purposeBounds[partType]
  if (!partBounds) {
    return {}
  }

  let maxBudget = partBounds.max ?? undefined

  // For visualization mode with non-challenge purposes, use dynamic max budget
  // This ensures skills the student is learning can appear in visualization
  if (
    partType === 'visualization' &&
    purpose !== 'challenge' &&
    studentMaxSkillCost !== undefined
  ) {
    // Use the higher of: static config max, or student's max skill cost
    // This allows learning skills to surface while still respecting config if higher
    if (maxBudget === undefined || studentMaxSkillCost > maxBudget) {
      maxBudget = studentMaxSkillCost
    }
  }

  return {
    min: partBounds.min ?? undefined,
    max: maxBudget,
  }
}
 
function createSlot(
  index: number,
  purpose: ProblemSlot['purpose'],
  baseConstraints: ReturnType<typeof getPhaseSkillConstraints>,
  partType: SessionPartType,
  config: PlanGenerationConfig,
  costCalculator?: SkillCostCalculator,
  studentMaxSkillCost?: number,
  comfortLevel = 0.3,
  comfortFactors?: TermCountExplanation['factors'],
  comfortAdjustment?: number,
  rawComfortLevel?: number,
  termCountScalingConfig?: TermCountScalingConfig
): ProblemSlot {
  // Get complexity bounds for this purpose + part type combination
  // Pass studentMaxSkillCost for dynamic visualization budget
  const complexityBounds = getComplexityBoundsForSlot(
    purpose,
    partType,
    config,
    studentMaxSkillCost
  )

  // Get dynamic term count range based on comfort level
  const { range: termCount, explanation: termCountExplanation } = getTermCountForPartType(
    partType,
    config,
    comfortLevel,
    comfortFactors,
    comfortAdjustment,
    rawComfortLevel,
    termCountScalingConfig
  )

  const constraints = {
    allowedSkills: baseConstraints.allowedSkills,
    targetSkills: baseConstraints.targetSkills,
    forbiddenSkills: baseConstraints.forbiddenSkills,
    termCount,
    digitRange: { min: 1, max: 2 },
    // Add complexity budget constraints based on purpose
    ...(complexityBounds.min !== undefined && {
      minComplexityBudgetPerTerm: complexityBounds.min,
    }),
    ...(complexityBounds.max !== undefined && {
      maxComplexityBudgetPerTerm: complexityBounds.max,
    }),
  }

  // Problem is generated later in buildSessionPart after shuffling
  return {
    slotId: crypto.randomUUID(),
    index,
    purpose,
    constraints,
    problem: undefined,
    complexityBounds,
    termCountExplanation,
  }
}
 
function calculateAvgTimePerProblem(
  sessions: Array<{ averageTimeMs: number | null; problemsAttempted: number }>
): number | null {
  const validSessions = sessions.filter((s) => s.averageTimeMs !== null && s.problemsAttempted > 0)
  if (validSessions.length === 0) return null

  const totalProblems = validSessions.reduce((sum, s) => sum + s.problemsAttempted, 0)
  const weightedSum = validSessions.reduce(
    (sum, s) => sum + s.averageTimeMs! * s.problemsAttempted,
    0
  )

  return Math.round(weightedSum / totalProblems / 1000) // Convert ms to seconds
}
 
function findSkillsNeedingReview(
  mastery: PlayerSkillMastery[],
  intervals: { mastered: number; practicing: number }
): PlayerSkillMastery[] {
  const now = Date.now()
  return mastery.filter((s) => {
    // Only consider skills that are being practiced
    if (!isActive(s.practiceLevel)) return false
    if (!s.lastPracticedAt) return false

    const daysSinceLastPractice =
      (now - new Date(s.lastPracticedAt).getTime()) / (1000 * 60 * 60 * 24)

    // Use the mastered interval for practicing skills (they're all "practicing" now)
    return daysSinceLastPractice > intervals.mastered
  })
}
 
/**
 * Build skill constraints from the student's actual mastered skills
 *
 * This creates constraints where:
 * - allowedSkills: all practicing skills (problems may ONLY use these skills)
 * - targetSkills: EMPTY (no targeting preference by default)
 * - forbiddenSkills: empty (don't exclude anything explicitly)
 *
 * IMPORTANT: targetSkills is empty by default, NOT all practicing skills.
 * This allows the differentiation between classic and adaptive modes:
 * - Classic: Uses these constraints directly → even skill distribution
 * - Adaptive: addWeakSkillsToTargets() adds only weak skills → focused practice
 */
function buildConstraintsFromPracticingSkills(
  practicingSkills: PlayerSkillMastery[]
): ReturnType<typeof getPhaseSkillConstraints> {
  const skills: Record<string, Record<string, boolean>> = {}

  for (const skill of practicingSkills) {
    // Parse skill ID format: "category.skillKey" like "fiveComplements.4=5-1" or "basic.+3"
    const [category, skillKey] = skill.skillId.split('.')

    if (category && skillKey) {
      if (!skills[category]) {
        skills[category] = {}
      }
      skills[category][skillKey] = true
    }
  }

  // allowedSkills: problems can ONLY use these skills (whitelist)
  // targetSkills: EMPTY by default - no targeting preference
  //
  // IMPORTANT: targetSkills MUST be empty here, not all skills!
  // When targetSkills = all skills, the problem generator accepts ANY problem
  // that uses allowed skills (since all allowed skills are also targets).
  // When targetSkills = empty, the problem generator generates an even
  // distribution across allowed skills.
  // When targetSkills = specific weak skills, the problem generator
  // ONLY accepts problems using those weak skills (100% hit rate).
  //
  // The differentiation between adaptive and classic modes happens because:
  // - Classic: Uses phaseConstraints (empty targetSkills) → even distribution
  // - Adaptive: addWeakSkillsToTargets() adds only weak skills → focused practice
  return {
    allowedSkills: skills,
    targetSkills: {}, // Empty by default - targeting added by addWeakSkillsToTargets()
    forbiddenSkills: {},
  } as ReturnType<typeof getPhaseSkillConstraints>
}
 
/**
 * Build constraints for targeting a specific skill.
 *
 * IMPORTANT: Uses the full baseConstraints.allowedSkills as the allowed skill set,
 * but sets only the target skill as targetSkills. This is critical because:
 *
 * - allowedSkills acts as a WHITELIST (problems can ONLY use these skills)
 * - Some skills have prerequisites (e.g., heavenBeadSubtraction needs heavenBead
 *   to first reach a state with ones digit >= 5)
 * - If we only allow the target skill, we can't use prerequisite skills to reach
 *   the state needed to use the target skill
 *
 * @param skill - The specific skill to target
 * @param baseConstraints - The student's full practicing skill constraints (used as whitelist)
 */
function buildConstraintsForSkill(
  skill: PlayerSkillMastery,
  baseConstraints: ReturnType<typeof getPhaseSkillConstraints>
): ReturnType<typeof getPhaseSkillConstraints> {
  // Parse skill ID to determine target
  // Format: "category.skillKey" like "fiveComplements.4=5-1"
  const [category, skillKey] = skill.skillId.split('.')

  const constraints = {
    // Use ALL practicing skills as the allowed set (whitelist)
    allowedSkills: baseConstraints.allowedSkills,
    // Target just the specific skill we want to reinforce/review
    targetSkills: {} as Record<string, Record<string, boolean>>,
    forbiddenSkills: baseConstraints.forbiddenSkills,
  }

  if (category && skillKey) {
    constraints.targetSkills[category] = { [skillKey]: true }
  }

  return constraints as ReturnType<typeof getPhaseSkillConstraints>
}
 
/**
 * Add weak skills to targetSkills in constraints.
 *
 * This modifies the constraints to ONLY target weak skills (identified by BKT),
 * replacing any existing targetSkills. The problem generator will specifically
 * prefer problems that exercise these weak skills, rather than spreading
 * attention across all allowed skills.
 *
 * IMPORTANT: We start with an EMPTY targetSkills, not a copy of existing ones.
 * This ensures weak skills get priority attention. If we copied all existing
 * targetSkills, weak skills would just be mixed in with everything else and
 * the problem generator wouldn't differentiate.
 *
 * @param baseConstraints - Base constraints with all practicing skills
 * @param weakSkillIds - Skill IDs identified as weak by BKT
 */
function addWeakSkillsToTargets(
  baseConstraints: ReturnType<typeof getPhaseSkillConstraints>,
  weakSkillIds: string[]
): ReturnType<typeof getPhaseSkillConstraints> {
  // Start with EMPTY targetSkills - we ONLY want to target weak skills
  // This makes the problem generator specifically prefer weak skill problems
  const targetSkills: Record<string, Record<string, boolean>> = {}

  // Add ONLY weak skills as targets
  for (const skillId of weakSkillIds) {
    const [category, skillKey] = skillId.split('.')
    if (category && skillKey) {
      if (!targetSkills[category]) {
        targetSkills[category] = {}
      }
      targetSkills[category][skillKey] = true
    }
  }

  return {
    allowedSkills: baseConstraints.allowedSkills,
    targetSkills,
    forbiddenSkills: baseConstraints.forbiddenSkills,
  } as ReturnType<typeof getPhaseSkillConstraints>
}
 
/**
 * Shuffle slots while keeping some focus problems clustered
 * This prevents too much context switching while still providing variety
 */
function intelligentShuffle(slots: ProblemSlot[]): ProblemSlot[] {
  // Group slots by purpose
  const focus = slots.filter((s) => s.purpose === 'focus')
  const reinforce = slots.filter((s) => s.purpose === 'reinforce')
  const review = slots.filter((s) => s.purpose === 'review')
  const challenge = slots.filter((s) => s.purpose === 'challenge')

  // Shuffle within each group
  const shuffledFocus = shuffleArray(focus)
  const shuffledReinforce = shuffleArray(reinforce)
  const shuffledReview = shuffleArray(review)
  const shuffledChallenge = shuffleArray(challenge)

  // Interleave: start with focus, mix in others throughout
  const result: ProblemSlot[] = []

  // Strategy: 3 focus, then 1 other, repeat
  let focusIdx = 0
  let reinforceIdx = 0
  let reviewIdx = 0
  let challengeIdx = 0

  while (
    focusIdx < shuffledFocus.length ||
    reinforceIdx < shuffledReinforce.length ||
    reviewIdx < shuffledReview.length ||
    challengeIdx < shuffledChallenge.length
  ) {
    // Add up to 3 focus problems
    for (let i = 0; i < 3 && focusIdx < shuffledFocus.length; i++) {
      result.push(shuffledFocus[focusIdx++])
    }

    // Add one from each other category
    if (reinforceIdx < shuffledReinforce.length) {
      result.push(shuffledReinforce[reinforceIdx++])
    }
    if (reviewIdx < shuffledReview.length) {
      result.push(shuffledReview[reviewIdx++])
    }
    if (challengeIdx < shuffledChallenge.length) {
      result.push(shuffledChallenge[challengeIdx++])
    }
  }

  // Re-index
  return result.map((slot, i) => ({ ...slot, index: i }))
}
 
function shuffleArray<T>(array: T[]): T[] {
  const result = [...array]
  for (let i = result.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[result[i], result[j]] = [result[j], result[i]]
  }
  return result
}
 
/**
 * Get user-friendly description for a session part type
 */
function getPartDescription(type: SessionPartType): string {
  switch (type) {
    case 'abacus':
      return 'Use Abacus'
    case 'visualization':
      return 'Mental Math (Visualization)'
    case 'linear':
      return 'Linear Math'
  }
}
 
function buildSummary(
  parts: SessionPart[],
  phase: CurriculumPhase | undefined,
  durationMinutes: number
): SessionSummary {
  const phaseInfo = phase ? getPhaseDisplayInfo(phase.id) : null

  const partSummaries: PartSummary[] = parts.map((part) => ({
    partNumber: part.partNumber,
    type: part.type,
    description: getPartDescription(part.type),
    problemCount: part.slots.length,
    estimatedMinutes: part.estimatedMinutes,
  }))

  const totalProblemCount = parts.reduce((sum, part) => sum + part.slots.length, 0)

  return {
    focusDescription: phaseInfo?.phaseName || 'General practice',
    totalProblemCount,
    estimatedMinutes: durationMinutes,
    parts: partSummaries,
  }
}