server.js 182 KB
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 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920
// Static file server + same-origin proxy to the fal.ai queue API.
// ponytail: keeping the proxy (rather than calling queue.fal.run directly
// from the browser) sidesteps having to verify fal's CORS behavior at all —
// same trick used for the MiniMax-native integration this replaced.
const http = require("http");
const https = require("https");
const fs = require("fs");
const path = require("path");
const os = require("os");
const crypto = require("crypto");
const { execFileSync } = require("child_process");

try {
  process.loadEnvFile(path.join(__dirname, ".env"));
} catch {
  // no .env file — fine, env vars may be set another way
}

const PORT = process.env.PORT || 8934;
const FAL_HOST = "queue.fal.run";
const H3_CONSOLE_BASE = process.env.H3_CONSOLE_BASE || "";
const H3_CONSOLE_TOKEN = process.env.H3_CONSOLE_TOKEN || "";
const H3_CONSOLE_URL = H3_CONSOLE_BASE ? new URL(H3_CONSOLE_BASE) : null;

// GLM Coding Plan — used only to expand a viewer's short chat prompt into a
// detailed shot-by-shot prompt before handing it to H3 (see optimizePrompt).
// Must hit the /api/coding/ path specifically — the plain /api/paas/ path
// bills against a different (pay-per-token) quota than the coding plan.
const GLM_API_KEY = process.env.GLM_API_KEY || "";
const GLM_HOST = "open.bigmodel.cn";
const GLM_PATH = "/api/coding/paas/v4/chat/completions";
const GLM_MODEL = "glm-5.3-flash";

// T24 credit topup. No test-mode key yet (2026-09-03: user said "先做一个
// mock,我明天再给你真实测试的 key") — see createCheckoutSession()'s doc
// comment for how the two paths split.
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY || "";
const STRIPE_WEBHOOK_SECRET = process.env.STRIPE_WEBHOOK_SECRET || "";
const APP_BASE_URL = process.env.APP_BASE_URL || `http://localhost:${process.env.PORT || 8934}`;

// T33 (dev-plan-5.md): fal.ai real-time compute for paid requests (需求文档
// 4.3 节双算力策略) — no key configured yet, same situation T24 was in with
// Stripe. See generateDanceVideoViaFal()'s doc comment for what's verified
// vs. still unverified (§8 item 1 / dev-plan-5.md §1.2 item 3: whether the
// one-step attribute_transfer prompt that works on H3 Console also works on
// fal's model — that needs a real call, not something code can assert).
const FAL_API_KEY = process.env.FAL_API_KEY || "";
// Overridable so tests can point these at a local mock (same reasoning as
// H3_CONSOLE_BASE) — default to fal's real, documented hosts.
const FAL_REST_BASE = process.env.FAL_REST_BASE || "https://rest.alpha.fal.ai";
const FAL_QUEUE_BASE = process.env.FAL_QUEUE_BASE || "https://queue.fal.run";
const FAL_MODEL_ID = "minimax/h3/reference-to-video";

// Standalone "人衣图生成" admin tool (admin-dressgen.html) — person 3-views +
// garment -> composite portrait via gpt-image-2, hosted behind 万界方舟's
// maas-openapi relay. NOT the same pipeline as generateDanceVideoViaFal
// above (that's H3/fal video); this is a one-shot image edit call.
//
// Contract confirmed against a real curl example the user supplied for the
// sibling /images/generations endpoint on this same host, plus this
// environment's own OPTIONS/GET probing of /images/edits (2026-09-03):
//   - host+path is maas-openapi.wanjiedata.com/api/v1/images/edits, NOT
//     fangzhou.wanjiedata.com/v1/images/edits (that first guess 405'd —
//     wrong host *and* wrong path; fangzhou is the docs/dashboard SPA, not
//     the API gateway. GET on the real /images/edits path 405s with an
//     explicit `Allow: POST` header from APISIX, confirming it's a real
//     registered route, not the SPA's catch-all).
//   - model id is the literal string "GPT Image 2" (with spaces) — the user
//     was warned a typo here gets WAF-blocked with 410 or "model
//     unauthorized", so don't "clean up" this string.
//   - this host's TLS chain does not validate from this machine (confirmed:
//     the user's own working curl needs -k) — generateDressImage() below
//     sends the request via a raw https.request with rejectUnauthorized
//     false scoped to just this one call, not a process-wide
//     NODE_TLS_REJECT_UNAUTHORIZED=0 (that would silently weaken every
//     other HTTPS call this server makes — Stripe, GLM, H3 Console, fal.ai).
//   - the /generations sibling responds JSON {data:[{url}]} (a short-lived
//     presigned URL, must be fetched immediately) and takes size/n as
//     top-level fields, not response_format (explicitly unsupported — don't
//     send it). /images/edits itself has NOT been call-tested (no example
//     for it specifically was available, only /generations + this
//     environment's unauthenticated OPTIONS/GET probing of the route's
//     existence) — its multipart shape here (image[] repeated, prompt,
//     model, size, n) mirrors OpenAI's own public /v1/images/edits
//     contract, which the user confirmed this vendor keeps in lockstep
//     with. First real authenticated call is still the actual proof.
//   - a real edit call takes 60-180s; the timeout must allow for 300s+.
const IMAGE2_API_KEY = process.env.IMAGE2_API_KEY || "";
const IMAGE2_API_BASE = process.env.IMAGE2_API_BASE || "https://maas-openapi.wanjiedata.com";
const IMAGE2_EDIT_PATH = "/api/v1/images/edits";
const IMAGE2_MODEL = "GPT Image 2";
const IMAGE2_SIZE = "1024x1536"; // within the ~157万-pixel cap the user measured; anything larger is silently downscaled
const IMAGE2_TIMEOUT_MS = 300000;
const IMAGE2_MIME = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp" };

// Second dressgen provider (2026-09-03) — admin-picked per task
// (record.provider) via the UI, or picked automatically as a fallback (see
// below).
//
// UPDATE (2026-09-03, later same day): the paragraph above originally said
// this would never auto-fallback on an IMAGE2 failure, reasoning that it'd
// silently re-route content around whichever provider's own moderation
// rejected it first. Asked directly about that tradeoff — with the
// concrete case in hand (a real-person-photo + swimwear task whose IMAGE2
// 400 looked like a moderation rejection, not a technical fault) — the
// product call came back "any failure auto-switches", overriding that
// stance. See runDressGenViews' fallback branch below. Recorded here so
// the next session doesn't rediscover this as a bug.
//
// Contract confirmed 2026-09-03 via real calls (not guessed): upload each
// image with POST {base}/api/v3/media/upload/binary (multipart, field
// "file") -> {data.download_url}; submit with POST {base}/api/v3/{model}
// (JSON: {prompt, images:[url,...]}) -> {data.id, data.urls.get}; poll
// data.urls.get until status is "completed" (-> data.outputs[0] is the
// result URL) or "failed" (-> data.error). No TLS quirks here (unlike
// IMAGE2) — plain fetch works.
const WAVESPEED_API_KEY = process.env.WAVESPEED_API_KEY || "";
const WAVESPEED_API_BASE = process.env.WAVESPEED_API_BASE || "https://api.wavespeed.ai";
const WAVESPEED_MODEL = "bytedance/seedream-v4/edit";
const WAVESPEED_POLL_INTERVAL_MS = Number(process.env.WAVESPEED_POLL_INTERVAL_MS) || 3000;
const WAVESPEED_TIMEOUT_MS = 180000; // observed ~30s in practice; generous headroom over that

const DRESSGEN_PROVIDERS = ["image2", "wavespeed"];
const DRESSGEN_DEFAULT_PROVIDER = "image2";

function dressGenProviderKeyMissing(provider) {
  if (provider === "wavespeed") return !WAVESPEED_API_KEY ? "WAVESPEED_API_KEY not configured" : null;
  return !IMAGE2_API_KEY ? "IMAGE2_API_KEY not configured" : null;
}

// Raw https.request wrapper (not fetch) so rejectUnauthorized:false can be
// scoped to exactly this one call — see the doc comment above. bodyBuffer
// may be omitted for a plain GET-style fetch (used for the presigned result
// URL, which may or may not share 万界's own broken cert chain — safer to
// go through the same relaxed path than to assume it doesn't). Dispatches
// on the URL's own protocol (not hardcoded to https) purely so tests can
// point IMAGE2_API_BASE at a plain-http local mock; the real vendor is
// always https.
function insecureHttpsRequest(urlString, { method = "GET", headers = {}, bodyBuffer } = {}) {
  return new Promise((resolve, reject) => {
    const url = new URL(urlString);
    const transport = url.protocol === "http:" ? http : https;
    const req = transport.request(
      {
        hostname: url.hostname,
        port: url.port || (url.protocol === "http:" ? 80 : 443),
        path: `${url.pathname}${url.search}`,
        method,
        rejectUnauthorized: false,
        headers,
        timeout: IMAGE2_TIMEOUT_MS,
      },
      (res) => {
        const chunks = [];
        res.on("data", (c) => chunks.push(c));
        res.on("end", () => resolve({ status: res.statusCode, buffer: Buffer.concat(chunks) }));
      }
    );
    req.on("timeout", () => req.destroy(new Error(`image2 request timed out after ${IMAGE2_TIMEOUT_MS}ms`)));
    req.on("error", reject);
    if (bodyBuffer) req.write(bodyBuffer);
    req.end();
  });
}

// 人物参考图最多 6 张定妆照(全身/脸部 × 正/侧/背),但不强制全传——传几张
// 算几张(至少 1 张)。gpt-image-2 的 edit 端点没有"生成 3 张不同视角"的原生
// 能力(同一次调用的 n 个输出是同一编辑的独立采样,不是可寻址的不同机位,
// CODEX-IMAGEGEN.md §4.3 也确认 edit 没有 batch 子命令),所以三个目标视角
// 分三次独立调用;每次调用都把用户实际上传的全部人物参考图 + 新衣服图一起
// 喂进去(不按 slot 精确配对),靠 prompt 里的目标视角文字区分三次调用要出
// 哪个角度。三次调用按顺序(依次)发起,不并发。
const DRESSGEN_PERSON_SLOTS = ["bodyFront", "bodySide", "bodyBack", "faceFront", "faceSide", "faceBack"];
const DRESSGEN_VIEWS = ["front", "side", "back"];
const DRESSGEN_VIEW_LABEL = { front: "正面", side: "侧面", back: "背面" };

function defaultDressgenPrompt(view) {
  const label = DRESSGEN_VIEW_LABEL[view];
  return (
    "前面的图是同一位人物的参考图(可能包含全身正/侧/背、脸正/侧/背等不同角度和部位,具体张数以实际上传为准),最后一张图是新服装参考图。" +
    `保持人物的脸部五官、发型、体型完全不变,仅将服装替换为新服装图所示服装,生成人物穿着新服装的${label}全身人物形象图。` +
    "鞋子沿用人物原有款式,不要更换;背景、地面材质、光照方向和色调都必须跟人物参考图里的场景保持一致——" +
    "不要换成纯色影棚背景,也不要换成另一个场景,三个视角(正/侧/背)用的是同一个背景。全身入镜。Size 1024x1536."
  );
}

// Runs (a subset of) DRESSGEN_VIEWS' edit calls in sequence against an
// already-created dressGenRecords row, writing progress back after every
// single view so admin-dressgen.html's poll (GET /api/admin/dressgen) can
// show "queued/generating/done/failed" per view while it's still running —
// not just a final result once the whole thing settles. Called
// fire-and-forget (`.catch(() => {})` at the call site) right after the
// HTTP response for POST /dressgen or POST /dressgen/:id/retry has already
// gone out; every failure mode here is recorded on the row itself, not
// thrown back to a caller that's no longer listening. `views` lets retry
// reprocess only the views that didn't succeed last time, without touching
// ones that already have an output.
async function runDressGenViews(recordId, imageAbsPaths, views) {
  for (const view of views) {
    const before = dressGenRecords.get(recordId);
    if (!before) return; // row was deleted mid-flight
    dressGenRecords.update(recordId, { viewStatus: { ...before.viewStatus, [view]: "generating" } });
    const provider = before.provider || DRESSGEN_DEFAULT_PROVIDER;
    let usedProvider = provider;
    try {
      let imageBuffer;
      try {
        imageBuffer = await generateDressImage({ imageAbsPaths, prompt: before.prompts[view], provider });
      } catch (err) {
        // Automatic fallback: default provider (image2) failed for any
        // reason -> retry once via wavespeed before giving up on this view.
        // See the note above generateDressImage's declaration for why.
        if (provider === DRESSGEN_DEFAULT_PROVIDER && !dressGenProviderKeyMissing("wavespeed")) {
          usedProvider = "wavespeed";
          imageBuffer = await generateDressImage({ imageAbsPaths, prompt: before.prompts[view], provider: "wavespeed" });
        } else {
          throw err;
        }
      }
      const { relPath } = placeInUploads(imageBuffer, "png");
      const after = dressGenRecords.get(recordId);
      if (!after) return;
      dressGenRecords.update(recordId, {
        outputImages: { ...after.outputImages, [view]: relPath },
        errors: { ...after.errors, [view]: null },
        viewStatus: { ...after.viewStatus, [view]: "done" },
        viewProvider: { ...(after.viewProvider || {}), [view]: usedProvider },
      });
    } catch (err) {
      const after = dressGenRecords.get(recordId);
      if (!after) return;
      dressGenRecords.update(recordId, {
        errors: { ...after.errors, [view]: err.message },
        viewStatus: { ...after.viewStatus, [view]: "failed" },
      });
    }
  }
  const final = dressGenRecords.get(recordId);
  if (!final) return;
  const succeeded = DRESSGEN_VIEWS.filter((v) => final.outputImages[v]).length;
  const status = succeeded === DRESSGEN_VIEWS.length ? "done" : succeeded > 0 ? "partial" : "failed";
  dressGenRecords.update(recordId, { status });
}

// Startup recovery, same idea as resumeDressupGenerations() above: a
// record can be sitting in "generating" if the process died mid-view.
// Unlike generationJobs there's no in-flight request id to reconnect to
// (image2/wavespeed calls are plain awaited HTTP round-trips inside
// runDressGenViews, nothing survives the process exiting) — every
// "queued"/"generating" view is unrecoverable, so it's marked failed with
// a distinguishable error, same as a real generation failure would be, and
// is one click to retry from either list or detail page.
function resumeDressgenTasks() {
  for (const record of dressGenRecords.list()) {
    const staleViews = DRESSGEN_VIEWS.filter((v) => record.viewStatus[v] === "queued" || record.viewStatus[v] === "generating");
    if (staleViews.length === 0) continue;
    const viewStatus = { ...record.viewStatus };
    const errors = { ...record.errors };
    for (const v of staleViews) {
      viewStatus[v] = "failed";
      errors[v] = "进程重启,任务丢失,请点重试";
    }
    const succeeded = DRESSGEN_VIEWS.filter((v) => record.outputImages[v]).length;
    const status = succeeded === DRESSGEN_VIEWS.length ? "done" : succeeded > 0 ? "partial" : "failed";
    dressGenRecords.update(record.id, { viewStatus, errors, status });
  }
}

// imageAbsPaths for a dressGenRecords row, recomputed from its own stored
// fields — used both at creation time and by retry (which reuses the
// original upload, no re-selecting images).
function dressGenImageAbsPaths(record) {
  const personPaths = DRESSGEN_PERSON_SLOTS.filter((f) => record[f]).map((f) => record[f]);
  return [...personPaths, record.garmentImage].map((p) => path.join(__dirname, p));
}

async function generateDressImage({ imageAbsPaths, prompt, provider }) {
  return provider === "wavespeed" ? generateDressImageViaWavespeed({ imageAbsPaths, prompt }) : generateDressImageViaImage2({ imageAbsPaths, prompt });
}

async function generateDressImageViaImage2({ imageAbsPaths, prompt }) {
  if (!IMAGE2_API_KEY) throw new Error("IMAGE2_API_KEY not configured");
  const form = new FormData();
  form.set("model", IMAGE2_MODEL);
  form.set("prompt", prompt);
  form.set("n", "1");
  form.set("size", IMAGE2_SIZE);
  for (const absPath of imageAbsPaths) {
    const ext = path.extname(absPath).slice(1).toLowerCase();
    form.append("image[]", new Blob([fs.readFileSync(absPath)], { type: IMAGE2_MIME[ext] || "application/octet-stream" }), path.basename(absPath));
  }
  // Encode via the platform's own FormData/Response to get correct
  // multipart boundary handling for free, then send over insecureHttpsRequest
  // (not fetch) — see IMAGE2_API_KEY's doc comment for why.
  const encoded = new Response(form);
  const contentType = encoded.headers.get("content-type");
  const bodyBuffer = Buffer.from(await encoded.arrayBuffer());

  const { status, buffer } = await insecureHttpsRequest(`${IMAGE2_API_BASE}${IMAGE2_EDIT_PATH}`, {
    method: "POST",
    headers: { Authorization: `Bearer ${IMAGE2_API_KEY}`, "Content-Type": contentType, "Content-Length": bodyBuffer.length },
    bodyBuffer,
  });
  const text = buffer.toString("utf8");
  if (status < 200 || status >= 300) throw new Error(`image2 edit failed: ${status} ${text.slice(0, 500)}`);
  let json;
  try {
    json = JSON.parse(text);
  } catch {
    throw new Error(`image2 edit returned non-JSON response: ${text.slice(0, 500)}`);
  }
  const item = json.data && json.data[0];
  if (!item) throw new Error("image2 edit response missing data[0]");
  if (item.b64_json) return Buffer.from(item.b64_json, "base64");
  if (item.url) {
    const { status: imgStatus, buffer: imgBuffer } = await insecureHttpsRequest(item.url);
    if (imgStatus < 200 || imgStatus >= 300) throw new Error(`failed to fetch generated image: ${imgStatus}`);
    return imgBuffer;
  }
  throw new Error("image2 edit response missing b64_json/url");
}

async function wavespeedUpload(absPath) {
  const ext = path.extname(absPath).slice(1).toLowerCase();
  const form = new FormData();
  form.set("file", new Blob([fs.readFileSync(absPath)], { type: IMAGE2_MIME[ext] || "application/octet-stream" }), path.basename(absPath));
  const res = await fetch(`${WAVESPEED_API_BASE}/api/v3/media/upload/binary`, {
    method: "POST",
    headers: { Authorization: `Bearer ${WAVESPEED_API_KEY}` },
    body: form,
  });
  const json = await res.json();
  if (!res.ok || !json.data || !json.data.download_url) throw new Error(`wavespeed upload failed: ${res.status} ${JSON.stringify(json).slice(0, 500)}`);
  return json.data.download_url;
}

async function generateDressImageViaWavespeed({ imageAbsPaths, prompt }) {
  if (!WAVESPEED_API_KEY) throw new Error("WAVESPEED_API_KEY not configured");
  const imageUrls = [];
  for (const absPath of imageAbsPaths) imageUrls.push(await wavespeedUpload(absPath));

  const submitRes = await fetch(`${WAVESPEED_API_BASE}/api/v3/${WAVESPEED_MODEL}`, {
    method: "POST",
    headers: { Authorization: `Bearer ${WAVESPEED_API_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ prompt, images: imageUrls }),
  });
  const submitJson = await submitRes.json();
  if (!submitRes.ok || !submitJson.data || !submitJson.data.urls || !submitJson.data.urls.get) {
    throw new Error(`wavespeed submit failed: ${submitRes.status} ${JSON.stringify(submitJson).slice(0, 500)}`);
  }
  const resultUrl = submitJson.data.urls.get;

  const deadline = Date.now() + WAVESPEED_TIMEOUT_MS;
  while (Date.now() < deadline) {
    await new Promise((r) => setTimeout(r, WAVESPEED_POLL_INTERVAL_MS));
    const pollRes = await fetch(resultUrl, { headers: { Authorization: `Bearer ${WAVESPEED_API_KEY}` } });
    const pollJson = await pollRes.json();
    const status = pollJson.data && pollJson.data.status;
    if (status === "completed") {
      const outputUrl = pollJson.data.outputs && pollJson.data.outputs[0];
      if (!outputUrl) throw new Error("wavespeed result completed but has no outputs[0]");
      const imgRes = await fetch(outputUrl);
      if (!imgRes.ok) throw new Error(`failed to fetch wavespeed output: ${imgRes.status}`);
      return Buffer.from(await imgRes.arrayBuffer());
    }
    if (status === "failed") throw new Error(`wavespeed generation failed: ${pollJson.data.error || "unknown error"}`);
    // otherwise still "created"/"processing" — keep polling
  }
  throw new Error(`wavespeed generation timed out after ${WAVESPEED_TIMEOUT_MS}ms`);
}

const MIME = {
  ".html": "text/html",
  ".js": "text/javascript",
  ".css": "text/css",
  ".json": "application/json",
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".png": "image/png",
  ".webp": "image/webp",
  ".mp4": "video/mp4",
};

const { syncLibrary } = require("./ingest.js");
const {
  UPLOADS_DIR,
  readRawBody,
  parseMultipart,
  boundaryFromContentType,
  sniffImageType,
  sniffVideoType,
  stripMetadataAndSave,
  saveVideoUpload,
  placeInUploads,
  forwardToH3Assets,
  forwardToFalAssets,
} = require("./uploads.js");
const { characters, garments, danceRefs, characterImages, generationJobs, moderationLog, blacklist, dressGenRecords } = require("./dressup-store.js");
const { buildStage2Prompt } = require("./prompt-template.js");
const { users: userStore, sessions: userSessions, creditLedger } = require("./db.js");
const { pricing } = require("./pricing.js");

const LIBRARY_PATH = path.join(__dirname, "library.json");
function getLibrary() {
  try {
    return JSON.parse(fs.readFileSync(LIBRARY_PATH, "utf8"));
  } catch {
    return [];
  }
}
function saveLibrary(lib) {
  fs.writeFileSync(LIBRARY_PATH, JSON.stringify(lib, null, 2));
}

// One-time backfill (2026-09 上架/下架): clips already QC'd "correct" before
// `published` existed count as already having passed verification, so they
// stay live in dance.html's random-fill pool instead of the room going
// quiet until someone re-publishes 57+ clips by hand.
(function backfillPublished() {
  const lib = getLibrary();
  let changed = false;
  for (const c of lib) {
    if (c.channel === "dance" && c.published === undefined) {
      c.published = c.qcStatus === "correct";
      changed = true;
    }
  }
  if (changed) saveLibrary(lib);
})();

const LIVE_STATE_PATH = path.join(__dirname, "live-state.json");
function loadLiveState() {
  try {
    const s = JSON.parse(fs.readFileSync(LIVE_STATE_PATH, "utf8"));
    return { schedule: s.schedule || [], promptQueue: s.promptQueue || [], chatMessages: s.chatMessages || [] };
  } catch {
    return { schedule: [], promptQueue: [], chatMessages: [] };
  }
}
function saveLiveState() {
  fs.writeFileSync(LIVE_STATE_PATH, JSON.stringify({ schedule, promptQueue, chatMessages }, null, 2));
}

// dance.html's own playout state (T11) — separate file/schedule/queue from
// live.html's (architecture.md 2.1: two independent channels, not shared).
// Per MVCP M.8, `schedule` here stores `videoId` references, not inlined
// clip snapshots like live's `schedule` does — dance clips join back to
// library.json at read time so an admin edit/takedown isn't stuck showing a
// stale copy.
//
// One live room per character (人物库多直播间, 2026-09): schedule/queue/
// priorityInbox used to be single global arrays (one shared room, always
// the one characters.isDefault character). They're now keyed by characterId
// — `danceRooms[characterId] = { schedule, queue, priorityInbox }` — a room
// exists for every character that has at least one channel:"dance" clip
// (getDanceRoomCharacterIds below), created lazily on first tick/request.
const DANCE_STATE_PATH = path.join(__dirname, "dance-state.json");
function loadDanceState() {
  try {
    const s = JSON.parse(fs.readFileSync(DANCE_STATE_PATH, "utf8"));
    if (s.rooms) return { danceRooms: s.rooms };
    // Pre-multi-room save file: migrate the one flat room forward onto
    // whichever character it actually belonged to (characters.isDefault),
    // rather than silently dropping in-flight generations/queued picks.
    const defaultCharacter = characters.list().find((c) => c.isDefault);
    const hadState = (s.schedule || []).length || (s.freeQueue || []).length || (s.priorityInbox || []).length;
    if (defaultCharacter && hadState) {
      return { danceRooms: { [defaultCharacter.id]: { schedule: s.schedule || [], queue: s.freeQueue || [], priorityInbox: s.priorityInbox || [] } } };
    }
    return { danceRooms: {} };
  } catch {
    return { danceRooms: {} };
  }
}
function saveDanceState() {
  fs.writeFileSync(DANCE_STATE_PATH, JSON.stringify({ rooms: danceRooms }, null, 2));
}
function getDanceRoom(characterId) {
  if (!danceRooms[characterId]) danceRooms[characterId] = { schedule: [], queue: [], priorityInbox: [] };
  return danceRooms[characterId];
}
// Every character with >=1 generated dance video gets a room automatically
// — no separate "publish/go-live" toggle (confirmed: "有视频就自动开间").
function getDanceRoomCharacterIds() {
  const ids = new Set(Object.keys(danceRooms));
  for (const clip of getLibrary()) if (clip.channel === "dance" && clip.characterId && clip.qcStatus !== "incorrect") ids.add(clip.characterId);
  return ids;
}
function getRoomViewers(characterId) {
  if (!danceViewers.has(characterId)) danceViewers.set(characterId, new Map());
  return danceViewers.get(characterId);
}

function readJsonBody(req) {
  return new Promise((resolve, reject) => {
    let data = "";
    req.on("data", (chunk) => (data += chunk));
    req.on("end", () => {
      try {
        resolve(data ? JSON.parse(data) : {});
      } catch (err) {
        reject(err);
      }
    });
    req.on("error", reject);
  });
}

// Stripe's webhook signature is computed over the exact raw request bytes
// (T24) — JSON.parse-then-restringify would not reproduce the same bytes,
// so this can't reuse readJsonBody for that one route.
function readRawTextBody(req) {
  return new Promise((resolve, reject) => {
    let data = "";
    req.on("data", (chunk) => (data += chunk));
    req.on("end", () => resolve(data));
    req.on("error", reject);
  });
}

// Minimal admin auth (dev-plan.md T6): one shared password from .env, an
// HttpOnly session cookie, no accounts/roles/DB — the account system in
// MVCP M.1/M.10 supersedes this in period 3. Sessions are in-memory only,
// so a process restart logs everyone out (acceptable for this stopgap).
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || "";
const ADMIN_SESSION_COOKIE = "admin_session";
const ADMIN_SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days, matches MVCP M.10's session TTL
const adminSessions = new Map(); // token -> expiresAt

function parseCookies(req) {
  const header = req.headers.cookie || "";
  const cookies = {};
  for (const pair of header.split(";")) {
    const idx = pair.indexOf("=");
    if (idx === -1) continue;
    cookies[pair.slice(0, idx).trim()] = decodeURIComponent(pair.slice(idx + 1).trim());
  }
  return cookies;
}

// T30: two accepted paths, either is enough — the ADMIN_PASSWORD cookie
// (T6, unchanged) stays as a fallback channel so nobody's locked out of the
// backend before any users.role='admin' account has been created by hand;
// requireUserSession + role='admin' (below, hoisted — same module scope) is
// the real per-admin identity path, MVCP M.10's stated rule for
// /api/admin/*. Calls requireUserSession before it's declared further down
// this file — fine, `function` declarations are fully hoisted.
function isAdminAuthed(req) {
  const token = parseCookies(req)[ADMIN_SESSION_COOKIE];
  if (token) {
    const expiresAt = adminSessions.get(token);
    if (expiresAt && expiresAt >= Date.now()) return true;
    adminSessions.delete(token);
  }
  const user = requireUserSession(req);
  return !!(user && user.role === "admin");
}

// Who to attribute an admin action to (T30's "credit_ledger 里能查到是哪个
//管理员做的") — null when the request came in over the legacy shared
// ADMIN_PASSWORD channel, which has no per-admin identity to attribute to.
function adminActorUserId(req) {
  const user = requireUserSession(req);
  return user && user.role === "admin" ? user.id : null;
}

// User account login (dev-plan-3.md T19; dressup-dance-room-mvcp.md
// M.1/M.10) — a separate cookie/session table from admin_session above, on
// purpose: this is for viewers, not the single shared admin credential, and
// the two must never be confused for one another.
const USER_SESSION_COOKIE = "user_session";
const USER_SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days, MVCP M.10
const EMAIL_VERIFY_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours, MVCP M.10

// T20: no email-delivery vendor has been picked yet (dev-plan-3.md §1's
// open question — SMTP vs. an HTTP-API provider like Resend/SendGrid).
// This is the one seam a real integration plugs into later; nothing else
// needs to change. For now it logs, and outside production also returns
// the link directly so registering can be tested end to end without a
// real inbox.
function sendVerificationEmail(email, token) {
  const verifyUrl = `/api/auth/verify?token=${token}`;
  console.log(`[email_verify] would send to ${email}: ${verifyUrl}`);
  return verifyUrl;
}

// T25: no vision-model vendor has been picked yet (dev-plan-4.md §1.2 item
// 2 — needed because mode 2's uploader has no admin around to hand-write
// garments.appearanceDescriptor the way admin_seed garments do). Same seam
// pattern as sendVerificationEmail above: today it's a fixed placeholder,
// swapping in a real vendor later is a one-function change, callers (T27)
// don't need to know the difference.
const VISION_API_KEY = process.env.VISION_API_KEY || "";
async function describeGarmentImage(absImagePath) {
  if (!VISION_API_KEY) return "用户上传的服装";
  throw new Error("vision vendor not implemented — set VISION_API_KEY only once a provider is wired up");
}

// T35 (dev-plan-5.md): same seam as describeGarmentImage above, for mode
// 3's uploaded face photos — appearanceDescriptor has no admin to
// hand-write it either, same underlying gap. Shares VISION_API_KEY (one
// vendor question, not two) since both are "describe an uploaded photo"
// calls to whatever vision model eventually gets picked.
async function describeCharacterImage(absImagePath) {
  if (!VISION_API_KEY) return "用户上传的人物形象";
  throw new Error("vision vendor not implemented — set VISION_API_KEY only once a provider is wired up");
}

// T26: same seam pattern, for image-content moderation (dev-plan-4.md §1.2
// item 1 — the requirements doc names a vendor as "TBD" and never actually
// lists it as its own task, so this is that gap filled in). Every call logs
// to moderation_log (M.9) regardless of which branch runs, so the audit
// trail exists before a real vendor does. `assetId` is the caller's own
// stable id for the upload (T27 passes the just-saved file's relPath, since
// at moderation time there's no garments.id yet — moderation runs before
// the garment record is created, per dev-plan-4.md T27's ordering).
const MODERATION_API_KEY = process.env.MODERATION_API_KEY || "";
async function moderateGarmentImage(absImagePath, assetId) {
  let verdict, reason;
  if (!MODERATION_API_KEY) {
    // No vendor configured: default-permissive placeholder pass (T2's
    // upload endpoint already enforces the real trust-boundary checks —
    // file type by magic bytes, 8MB cap, EXIF-stripped re-encode — this is
    // only the *content* check, which nothing here can actually perform
    // without a vendor).
    verdict = "auto_pass";
    reason = null;
  } else {
    throw new Error("moderation vendor not implemented — set MODERATION_API_KEY only once a provider is wired up");
  }
  moderationLog.create({ assetType: "garment_upload", assetId, verdict, reason, reviewedBy: "system" });
  return { approved: verdict === "auto_pass", verdict, reason };
}

// T32 (dev-plan-5.md): same seam pattern as T26 above, but for mode 3's
// uploaded face photos against a "sensitive figure" blacklist (需求文档 5
// 节 — e.g. filtering politically sensitive likenesses), not general image
// content. No vendor has been picked (needs research, dev-plan-5.md §1.2
// item 1). Default policy when unconfigured is default-permissive
// (auto_pass) — deliberately confirmed with the user rather than assumed,
// since the risk profile here (a real uploaded face, potentially a
// sensitive public figure) is not the same as T26's garment photos, where
// a wrong default-pass is low-stakes. Do not silently change this default
// without asking again.
const FACE_BLACKLIST_API_KEY = process.env.FACE_BLACKLIST_API_KEY || "";
async function moderateFaceBlacklist(absImagePath, assetId) {
  let verdict, reason;
  if (!FACE_BLACKLIST_API_KEY) {
    verdict = "auto_pass";
    reason = null;
  } else {
    throw new Error("face-blacklist vendor not implemented — set FACE_BLACKLIST_API_KEY only once a provider is wired up");
  }
  moderationLog.create({ assetType: "character_upload", assetId, verdict, reason, reviewedBy: "system" });
  return { approved: verdict === "auto_pass", verdict, reason };
}

// T21: mirrors live.html/dance.html's own setCookie() exactly (path=/,
// samesite=lax, no httponly, max-age in seconds, 365-day TTL) — these are
// the same viewer_uid/viewer_nickname cookies those pages already read
// with plain client-side JS, not a new cookie scheme.
function viewerIdentityCookie(name, value) {
  return `${name}=${encodeURIComponent(value)}; Max-Age=${365 * 86400}; Path=/; SameSite=Lax`;
}

function hashPassword(password) {
  const salt = crypto.randomBytes(16).toString("hex");
  const hash = crypto.scryptSync(password, salt, 64).toString("hex");
  return `${salt}:${hash}`;
}

function verifyPassword(password, stored) {
  const [salt, hash] = (stored || "").split(":");
  if (!salt || !hash) return false;
  const candidate = crypto.scryptSync(password, salt, 64);
  const expected = Buffer.from(hash, "hex");
  // scryptSync's output length is fixed by the third argument above, so
  // both buffers are always the same length — timingSafeEqual would throw
  // otherwise, but that can't happen here.
  return crypto.timingSafeEqual(candidate, expected);
}

// Returns the logged-in user (plain object, MVCP M.1 shape) or null. Free
// endpoints (/api/dance/*) don't call this at all — only routes that
// actually need an account (T20's email verify, T21's identity binding,
// anything paid in period 4) do.
function requireUserSession(req) {
  const token = parseCookies(req)[USER_SESSION_COOKIE];
  if (!token) return null;
  const session = userSessions.findByToken(token);
  if (!session || session.kind !== "session") return null;
  return userStore.get(session.userId);
}

// Generic CRUD router for the three cold-start asset libraries (T3-T5) —
// GET list / POST create / PATCH update / DELETE, backed by store.js. The
// three entities' shapes differ (see MVCP M.3/M.4/M.5) but the routing and
// validation boilerplate is identical, so this is mounted three times below
// instead of copy-pasted.
function mountCrud(prefix, store, opts = {}) {
  const { requiredFields = [], sanitize = (b) => b, onCreate, onUpdate, onDelete } = opts;

  function missingField(body) {
    return requiredFields.find((f) => {
      const v = body[f];
      return v === undefined || v === null || (typeof v === "string" && !v.trim());
    });
  }

  return function handle(pathname, req, res) {
    if (pathname === prefix && req.method === "GET") {
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(store.list()));
      return true;
    }

    if (pathname === prefix && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          const missing = missingField(body);
          if (missing) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: `${missing} required` }));
            return;
          }
          const item = store.create(sanitize(body));
          if (onCreate) onCreate(item, store);
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(item));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return true;
    }

    if (pathname.startsWith(`${prefix}/`) && req.method === "PATCH") {
      const id = pathname.slice(prefix.length + 1);
      readJsonBody(req)
        .then((body) => {
          // Partial update: only reject an explicit blank-out of a required
          // field, not the field's mere absence from this patch.
          const missing = requiredFields.find((f) => f in body && missingField({ [f]: body[f] }) === f);
          if (missing) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: `${missing} required` }));
            return;
          }
          const updated = store.update(id, sanitize(body, true));
          if (!updated) {
            res.writeHead(404, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "not found" }));
            return;
          }
          if (onUpdate) onUpdate(updated, store);
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(updated));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return true;
    }

    if (pathname.startsWith(`${prefix}/`) && req.method === "DELETE") {
      const id = pathname.slice(prefix.length + 1);
      const existing = store.get(id);
      const removed = store.remove(id);
      if (removed && onDelete) onDelete(existing, store);
      res.writeHead(removed ? 200 : 404, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ deleted: removed }));
      return true;
    }

    return false;
  };
}

// isDefault is a singleton across the whole characters library (2 节:
// "第一期只允许同时有一个人物被设为默认") — enforced here rather than in
// store.js, which stays schema-agnostic.
function unsetOtherDefaultCharacters(item, store) {
  if (!item.isDefault) return;
  for (const c of store.list()) {
    if (c.id !== item.id && c.isDefault) store.update(c.id, { isDefault: false });
  }
}

const charactersCrud = mountCrud("/api/admin/characters", characters, {
  requiredFields: ["name", "imageUrl", "appearanceDescriptor"],
  sanitize: (body, isPatch) =>
    isPatch
      ? body
      : {
          name: body.name,
          imageUrl: body.imageUrl,
          tags: Array.isArray(body.tags) ? body.tags : [],
          source: "admin_seed",
          ownerUserId: null,
          appearanceDescriptor: body.appearanceDescriptor,
          isDefault: Boolean(body.isDefault),
          moderationStatus: "auto_passed",
          totalSegments: null,
          remainingSegments: null,
          status: "active",
        },
  onCreate: (item, store) => {
    unsetOtherDefaultCharacters(item, store);
    // Mirrors the single image the add-character form just uploaded into
    // the gallery as its first/cover row, so admin_seed characters created
    // the old one-image way still show up correctly in the image manager.
    if (item.imageUrl) characterImages.create({ characterId: item.id, imageUrl: item.imageUrl, angleLabel: "主图", isCover: true });
  },
  onUpdate: unsetOtherDefaultCharacters,
  // character-images has no FK constraint of its own (store.js is
  // schema-agnostic) — deleting a character would otherwise leave its
  // gallery rows orphaned forever.
  onDelete: (character) => {
    if (!character) return;
    for (const img of characterImages.list().filter((i) => i.characterId === character.id)) characterImages.remove(img.id);
  },
});

const garmentsCrud = mountCrud("/api/admin/garments", garments, {
  requiredFields: ["name", "imageUrl", "appearanceDescriptor"],
  sanitize: (body, isPatch) =>
    isPatch
      ? body
      : {
          name: body.name,
          category: body.category || "",
          thumbnailUrl: body.thumbnailUrl || body.imageUrl,
          imageUrl: body.imageUrl,
          appearanceDescriptor: body.appearanceDescriptor,
          source: "admin_seed",
          ownerUserId: null,
          moderationStatus: "approved",
          isActive: body.isActive === undefined ? true : Boolean(body.isActive),
        },
});

const danceRefsCrud = mountCrud("/api/admin/dance-refs", danceRefs, {
  requiredFields: ["name", "videoUrl", "motionDescriptor"],
  sanitize: (body, isPatch) =>
    isPatch
      ? body
      : {
          name: body.name,
          videoUrl: body.videoUrl,
          styleTags: Array.isArray(body.styleTags) ? body.styleTags : [],
          durationSec: body.durationSec || null,
          motionDescriptor: body.motionDescriptor,
          copyrightSource: "test_placeholder",
          isActive: body.isActive === undefined ? true : Boolean(body.isActive),
        },
});

// Setting isCover on one image unsets it on the character's other images
// (singleton-per-characterId, same idea as unsetOtherDefaultCharacters) and
// mirrors the url onto characters.imageUrl. h3AssetUrl/falAssetUrl are
// forward-once caches keyed off the OLD imageUrl (ensureH3AssetUrl/
// ensureFalAssetUrl below) — a cover swap must clear them or generation
// keeps sending the previous photo.
function syncCoverToCharacter(image, store) {
  if (!image.isCover) return;
  for (const img of store.list()) {
    if (img.id !== image.id && img.characterId === image.characterId && img.isCover) store.update(img.id, { isCover: false });
  }
  characters.update(image.characterId, { imageUrl: image.imageUrl, h3AssetUrl: null, falAssetUrl: null });
}

// Deleting the cover image must not leave characters.imageUrl pointing at a
// gallery row that no longer exists — promote whatever's left, if anything.
function promoteNewCoverOnDelete(deletedImage, store) {
  if (!deletedImage || !deletedImage.isCover) return;
  const remaining = store.list().filter((img) => img.characterId === deletedImage.characterId);
  if (remaining.length === 0) return;
  store.update(remaining[0].id, { isCover: true });
  characters.update(deletedImage.characterId, { imageUrl: remaining[0].imageUrl, h3AssetUrl: null, falAssetUrl: null });
}

const characterImagesCrud = mountCrud("/api/admin/character-images", characterImages, {
  requiredFields: ["characterId", "imageUrl"],
  sanitize: (body, isPatch) =>
    isPatch
      ? body
      : { characterId: body.characterId, imageUrl: body.imageUrl, angleLabel: body.angleLabel || "", isCover: Boolean(body.isCover) },
  onCreate: (item, store) => {
    // A character's first image has nothing to be "cover" relative to —
    // make it the cover automatically instead of leaving the gallery
    // coverless until the admin remembers to flip a checkbox.
    const siblingCount = store.list().filter((img) => img.characterId === item.characterId).length;
    if (siblingCount === 1 && !item.isCover) {
      store.update(item.id, { isCover: true });
      item.isCover = true;
    }
    syncCoverToCharacter(item, store);
  },
  onUpdate: syncCoverToCharacter,
  onDelete: promoteNewCoverOnDelete,
});

function h3ConsoleFetch(pathAndQuery, options) {
  return new Promise((resolve, reject) => {
    const proxyReq = http.request(
      {
        hostname: H3_CONSOLE_URL.hostname,
        port: H3_CONSOLE_URL.port || 80,
        path: `${H3_CONSOLE_URL.pathname}${pathAndQuery}`,
        method: (options && options.method) || "GET",
        headers: { Authorization: `Bearer ${H3_CONSOLE_TOKEN}`, "Content-Type": "application/json" },
      },
      (proxyRes) => {
        let data = "";
        proxyRes.on("data", (c) => (data += c));
        proxyRes.on("end", () => {
          try {
            resolve(JSON.parse(data));
          } catch (err) {
            reject(err);
          }
        });
      }
    );
    proxyReq.on("error", reject);
    if (options && options.body) proxyReq.write(JSON.stringify(options.body));
    proxyReq.end();
  });
}

// timeoutMs default matches the original text-only prompt-optimize use —
// the QC caller (multi-image, much bigger payload) passes a longer one.
function glmChat(messages, timeoutMs = 15000) {
  return new Promise((resolve, reject) => {
    const body = JSON.stringify({ model: GLM_MODEL, messages, temperature: 0.7 });
    const req = https.request(
      {
        hostname: GLM_HOST,
        path: GLM_PATH,
        method: "POST",
        headers: { Authorization: `Bearer ${GLM_API_KEY}`, "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) },
      },
      (res) => {
        let data = "";
        res.on("data", (c) => (data += c));
        res.on("end", () => {
          try {
            resolve(JSON.parse(data));
          } catch (err) {
            reject(err);
          }
        });
      }
    );
    req.on("error", reject);
    req.setTimeout(timeoutMs, () => req.destroy(new Error("GLM request timed out")));
    req.write(body);
    req.end();
  });
}

// ---- T24: Stripe topup, with a mock fallback until a real test-mode key
// exists (2026-09-03: user said "先做一个 mock,我明天再给你真实测试的
// key") — createCheckoutSession() is the single seam both paths sit
// behind, matching T20/T25/T26's "one pluggable function" precedent. ----
const pendingMockCheckouts = new Map(); // token -> {userId, tierKey, expiresAt}
const MOCK_CHECKOUT_TTL_MS = 30 * 60 * 1000;

// Both the mock path (GET /api/credits/mock-checkout) and the real path
// (POST /api/credits/webhook) end up here — one place that actually moves
// money, so there's exactly one code path responsible for the
// ledger/idempotency bookkeeping (topup()'s paymentRef dedup, db.js).
function completeTopup({ userId, tierKey, paymentRef }) {
  const tier = pricing.get(tierKey);
  if (!tier || tier.kind !== "topup_tier" || !tier.isActive) {
    throw new Error(`unknown or inactive topup tier: ${tierKey}`);
  }
  return creditLedger.topup({ userId, amount: tier.credits, reason: "topup", paymentRef });
}

// Real Stripe path: plain REST via global fetch, no stripe npm SDK — this
// project has no package.json/dependencies, and Stripe's Checkout Sessions
// API is documented as plain form-encoded REST (same "use fetch, not a new
// dependency" call as forwardToH3Assets in uploads.js). Untested against a
// real Stripe account as of this commit — no test-mode key exists yet, see
// dev-plan-4.md §1.2 item 4.
async function createRealStripeCheckoutSession({ userId, tierKey, tier }) {
  const params = new URLSearchParams({
    mode: "payment",
    "line_items[0][quantity]": "1",
    "line_items[0][price_data][currency]": "usd",
    "line_items[0][price_data][unit_amount]": String(tier.priceCents),
    "line_items[0][price_data][product_data][name]": `${tier.credits} credits`,
    success_url: `${APP_BASE_URL}/dance.html?topup=success`,
    cancel_url: `${APP_BASE_URL}/dance.html?topup=cancelled`,
    "metadata[userId]": userId,
    "metadata[tierKey]": tierKey,
  });
  const res = await fetch("https://api.stripe.com/v1/checkout/sessions", {
    method: "POST",
    headers: { Authorization: `Bearer ${STRIPE_SECRET_KEY}`, "Content-Type": "application/x-www-form-urlencoded" },
    body: params,
  });
  const session = await res.json();
  if (!res.ok) throw new Error(session.error?.message || "Stripe checkout session creation failed");
  return session.url;
}

// Mock path: no real payment happens, but the whole checkout -> redirect ->
// credited loop is real and testable today — T29's UI and topup()'s own
// dedup logic don't need to wait on a real Stripe key to be built and
// exercised end to end.
function createMockCheckoutUrl({ userId, tierKey }) {
  const token = crypto.randomUUID();
  pendingMockCheckouts.set(token, { userId, tierKey, expiresAt: Date.now() + MOCK_CHECKOUT_TTL_MS });
  return `/api/credits/mock-checkout?token=${token}`;
}

async function createCheckoutSession({ userId, tierKey }) {
  const tier = pricing.get(tierKey);
  if (!tier || tier.kind !== "topup_tier" || !tier.isActive) {
    throw new Error(`unknown or inactive topup tier: ${tierKey}`);
  }
  if (!STRIPE_SECRET_KEY) return { url: createMockCheckoutUrl({ userId, tierKey }) };
  return { url: await createRealStripeCheckoutSession({ userId, tierKey, tier }) };
}

// Stripe's documented signature scheme (Stripe-Signature header:
// "t=<timestamp>,v1=<hex hmac>"): HMAC-SHA256 over "<timestamp>.<raw body>"
// with the webhook signing secret, compared in constant time. Hand-rolled
// rather than the stripe SDK for the same "no new dependency" reason as
// the rest of this integration.
function verifyStripeWebhookSignature(rawBody, signatureHeader, secret) {
  if (!signatureHeader) return false;
  const parts = Object.fromEntries(
    signatureHeader
      .split(",")
      .map((kv) => kv.split("="))
      .filter((kv) => kv.length === 2)
  );
  if (!parts.t || !parts.v1) return false;
  const expected = crypto.createHmac("sha256", secret).update(`${parts.t}.${rawBody}`).digest("hex");
  let expectedBuf, actualBuf;
  try {
    expectedBuf = Buffer.from(expected, "hex");
    actualBuf = Buffer.from(parts.v1, "hex");
  } catch {
    return false;
  }
  return expectedBuf.length === actualBuf.length && crypto.timingSafeEqual(expectedBuf, actualBuf);
}

// Distilled from docs/h3skill.md (MiniMax's own H3 prompt-writing methodology) down to the one
// path that applies here: T2VA (no reference images — every chat prompt is plain text) on a clip
// fixed at ~10s (H3_GEN_PARAMS.frames / FPS). At that length it's one continuous shot, never a
// multi-cut montage — an earlier version asked for "shot-by-shot" and reliably got 4-5 fake cuts
// with timestamps running past the clip's own length, which the model can't actually deliver.
const PROMPT_OPTIMIZE_SYSTEM = `You are writing H3 text-to-video generation prompts (T2VA mode — no
reference images, pure text-to-video). Expand the user's short request (may be in Chinese or English)
into the official H3 three-field format, in this exact order, using these exact field labels:

integrated_multimodal_description: [Shot 1] one short style statement, e.g. "Live-action, cinematic."
Then describe, in one continuous unbroken shot (the clip is only about 10 seconds long — never split
into multiple shots or write more than [Shot 1]): the setting, the subject's specific action, and ONE
dominant camera movement using this vocabulary — Zoom In/Out, Push In/Pull Out, Pan Left/Right, Truck
Left/Right, Tilt Up/Down, Pedestal Up/Down, Arc Shot, Tracking Shot, Static Shot, Shake Slightly/
Strongly, POV, Roll Clockwise/Counterclockwise — stated as type + amplitude (small/large) + speed
(slow/fast). Describe light concretely: where it comes from, what it hits, what effect it creates.
Never use hollow quality words alone (8K, HD, masterpiece, stunning, cinematic used alone, beautiful,
high quality) — replace them with what is actually visible. 60-100 English words.

overall_soundscape: 1-4 English sentences describing the ambient environmental sound the scene would
naturally have.

non_diegetic_music: 1-3 English sentences describing the score the audience (not the characters) hears,
or exactly "N/A" if none fits.

Output only these three labeled fields in this exact order and exact labels, nothing else — no
preamble, no extra commentary, no markdown formatting.`;

// Best-effort — a viewer's short chat line ("一只猫跳舞") makes for a weak
// H3 prompt on its own. Never let a GLM outage or slow response block
// generation: on any failure this just falls back to the original text.
async function optimizePrompt(userPrompt) {
  if (!GLM_API_KEY) return userPrompt;
  try {
    const res = await glmChat([
      { role: "system", content: PROMPT_OPTIMIZE_SYSTEM },
      { role: "user", content: userPrompt },
    ]);
    const text = res.choices && res.choices[0] && res.choices[0].message && res.choices[0].message.content;
    return text ? text.trim() : userPrompt;
  } catch {
    return userPrompt;
  }
}

// ---- Dance video QC (2026-09): AI-assisted check that a generated dance
// clip actually shows the right garment on a consistent character from
// first frame to last. Reuses glmChat() — confirmed live (2026-09-07) that
// the coding-plan endpoint/glm-5.3-flash model accepts multiple image_url
// content parts and correctly distinguishes them, so no new vision vendor
// is needed. ffmpeg extracts frames locally, same "shell out to a system
// media tool" pattern uploads.js already uses for sips.
function imageDataUrl(absPath) {
  const ext = path.extname(absPath).slice(1).toLowerCase();
  const mime = ext === "jpg" ? "jpeg" : ext;
  return `data:image/${mime};base64,${fs.readFileSync(absPath).toString("base64")}`;
}

// Reference photos (character/garment uploads) can be several MB at full
// resolution — 5 of those in one GLM request is what pushed the very first
// QC call past a 15s timeout. Downscales via `sips` (same tool
// stripMetadataAndSave already shells out to) before encoding; falls back
// to the original file if sips fails for any reason rather than blocking
// the whole check on a resize hiccup.
function resizedImageDataUrl(absPath, maxDim) {
  const tmpPath = path.join(os.tmpdir(), `qc-resize-${crypto.randomUUID()}${path.extname(absPath) || ".jpg"}`);
  try {
    execFileSync("sips", ["-Z", String(maxDim), absPath, "--out", tmpPath], { stdio: "pipe" });
    return imageDataUrl(tmpPath);
  } catch {
    return imageDataUrl(absPath);
  } finally {
    fs.rm(tmpPath, { force: true }, () => {});
  }
}

// Goes through this clip's own /lib/video/:id route rather than duplicating
// its source dispatch (manual/fal videoUrl redirect vs H3 Console proxy) —
// whatever a viewer's <video> tag would actually receive is what gets QC'd.
async function downloadClipVideo(clipId) {
  const res = await fetch(`http://localhost:${PORT}/lib/video/${clipId}`);
  if (!res.ok) throw new Error(`failed to fetch clip video: HTTP ${res.status}`);
  const buf = Buffer.from(await res.arrayBuffer());
  const tmpPath = path.join(os.tmpdir(), `qc-${clipId}-${crypto.randomUUID()}.mp4`);
  fs.writeFileSync(tmpPath, buf);
  return tmpPath;
}

// Start / middle / near-end — enough to catch a garment swap or identity
// drift partway through without paying to sample every frame.
function extractQcFrames(videoAbsPath, durationSec) {
  const dur = durationSec && durationSec > 1 ? durationSec : 10;
  const timestamps = [0.5, Math.max(0.5, dur / 2), Math.max(0.5, dur - 0.5)];
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "qc-frames-"));
  try {
    return timestamps.map((t, i) => {
      const outPath = path.join(tmpDir, `frame${i}.jpg`);
      // scale=480:-2 caps width at the clip's own native width (DANCE_GEN_PARAMS
      // is 480x832) — no upscaling, just keeps a wider source from ballooning
      // the request; -2 keeps height even (required by some encoders/filters).
      execFileSync("ffmpeg", ["-y", "-ss", String(t), "-i", videoAbsPath, "-frames:v", "1", "-vf", "scale='min(480,iw)':-2", "-q:v", "3", outPath], { stdio: "pipe" });
      return imageDataUrl(outPath);
    });
  } finally {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  }
}

const QC_PROMPT = `你是短视频质检员。你会收到 5 张图片,按顺序是:
1. 人物参考照(这个角色应有的脸型、发型、体态)
2. 衣服参考照(视频里应该穿着的服装)
3-5. 同一条跳舞视频的开头、中间、结尾三帧截图

请检查两件事:
1. 视频里穿的衣服,颜色/款式/剪裁是否与第 2 张衣服参考照一致
2. 从开头到结尾,人物的脸型、发型、体态是否与第 1 张人物参考照保持一致,且开头/中间/结尾三帧之间人物本身是否连贯、没有跑偏或变成另一个人

只输出一个 JSON 对象,不要输出其他任何文字或 markdown 代码块标记,格式严格为:
{"verdict":"correct"} 或 {"verdict":"incorrect","note":"一两句话说明具体是衣服问题还是人物问题,哪里不对"}`;

function parseQcVerdict(text) {
  const match = text.match(/\{[\s\S]*\}/);
  if (!match) throw new Error("GLM response contained no JSON object");
  const parsed = JSON.parse(match[0]);
  if (parsed.verdict !== "correct" && parsed.verdict !== "incorrect") throw new Error(`unexpected verdict: ${parsed.verdict}`);
  return { verdict: parsed.verdict, note: parsed.verdict === "incorrect" ? String(parsed.note || "").trim() || "AI 未说明具体原因" : "" };
}

// Runs the AI check for one dance clip. Callers write the result onto the
// library record themselves — this only returns it.
async function runDanceClipQc(clip) {
  if (!GLM_API_KEY) throw new Error("GLM_API_KEY not configured");
  const character = characters.get(clip.characterId);
  const garment = garments.get(clip.garmentId);
  if (!character || !garment) throw new Error("clip is missing its character/garment reference");

  const videoPath = await downloadClipVideo(clip.id);
  let frames;
  try {
    frames = extractQcFrames(videoPath, clip.duration);
  } finally {
    fs.unlinkSync(videoPath);
  }

  const refImages = [character.imageUrl, garment.imageUrl].map((relPath) => resizedImageDataUrl(path.join(__dirname, relPath), 480));
  const res = await glmChat(
    [
      {
        role: "user",
        content: [{ type: "text", text: QC_PROMPT }, ...[...refImages, ...frames].map((url) => ({ type: "image_url", image_url: { url } }))],
      },
    ],
    60000 // 5 images is a much bigger payload than optimizePrompt's text-only default use
  );
  const text = res.choices && res.choices[0] && res.choices[0].message && res.choices[0].message.content;
  if (!text) throw new Error(`GLM returned no content: ${JSON.stringify(res).slice(0, 300)}`);
  const { verdict, note } = parseQcVerdict(text);
  return { qcStatus: verdict, qcNote: note ? `[AI] ${note}` : "" };
}

// In-memory only (not persisted) — a batch is cheap enough to just re-run
// if the server restarts mid-way, unlike generationJobs' real H3 spend.
const qcBatchJobs = new Map(); // batchId -> {total, checked, results:[{clipId,qcStatus,qcNote,error?}], status:"running"|"done", cancelled}

async function runQcBatch(batchId, clipIds) {
  const job = qcBatchJobs.get(batchId);
  for (const clipId of clipIds) {
    if (job.cancelled) break;
    const lib = getLibrary();
    const clip = lib.find((c) => c.id === clipId);
    if (!clip) {
      job.results.push({ clipId, error: "clip no longer exists" });
      job.checked++;
      continue;
    }
    try {
      const { qcStatus, qcNote } = await runDanceClipQc(clip);
      clip.qcStatus = qcStatus;
      clip.qcNote = qcNote;
      clip.published = qcStatus === "correct"; // 通过验证的自动上架
      saveLibrary(lib);
      job.results.push({ clipId, qcStatus, qcNote });
    } catch (err) {
      job.results.push({ clipId, error: err.message });
    }
    job.checked++;
    // Sequential, not concurrent, with a small gap — GLM is far more
    // resilient than H3 Console, but a burst of ffmpeg child processes
    // plus large-image requests firing all at once is still worth avoiding.
    await new Promise((r) => setTimeout(r, 800));
  }
  job.status = "done";
}

// ---- Live channel: shared virtual playhead + prompt queue ----
// Persisted to live-state.json (see saveLiveState/loadLiveState) so a
// restart resumes the schedule instead of starting cold; ensureSchedule's
// own past-entry trimming naturally handles a state file that's gone stale
// (server was down long enough that every persisted entry is in the past).
const FILLER_DURATION_MS = 30000; // keep the schedule filled at least this far ahead
const H3_GEN_PARAMS = { width: 480, height: 832, frames: 240, steps: 20, turbo: false, seed: 0 };
const FPS = 24;

// dance.html's own generation params (architecture.md 2.4: each channel
// keeps an independent H3_GEN_PARAMS even though the values happen to
// match live.html's today — don't merge the two constants).
const DANCE_GEN_PARAMS = { width: 480, height: 832, frames: 240, steps: 20, turbo: false, seed: 0 };

const initialLiveState = loadLiveState();
let schedule = initialLiveState.schedule; // [{clip, startAt, endAt, requestedBy?}]
let promptQueue = initialLiveState.promptQueue; // [{id, prompt, nickname?, status, clip?, error?, submittedAt, h3JobId?}]
let chatMessages = initialLiveState.chatMessages; // [{id, uid, nickname, text, createdAt, status}]

const initialDanceState = loadDanceState();
// { [characterId]: { schedule: [{videoId, startAt, endAt, requestedBy?}],
//                     queue: [{id, garmentId, characterId, nickname?, status, jobId?, videoId?, error?, submittedAt, votes}],
//                     priorityInbox: [{videoId, requestedBy}] } } — one room
// per character (see getDanceRoom above). priorityInbox: T34 (dev-plan-5.md;
// schema M.8) paid_boost (mode 3) clips land here once ready, never in a
// room's vote-ranked queue — that room's pickNextDanceClip drains this
// first, unconditionally, every tick.
let danceRooms = initialDanceState.danceRooms;

// How often ensureSchedule/ensureDanceSchedule tick — configurable so tests
// don't have to wait out a real 2s to see a schedule fill.
const SCHEDULE_TICK_MS = Number(process.env.SCHEDULE_TICK_MS) || 2000;

// ---- chat + moderation ----
// ponytail: a starter blocklist, not a real content-policy list — swap in
// whatever the actual moderation requirements are. Substring match on the
// lowercased text; cheap and deterministic. Anything this doesn't catch
// (content that's fine as *text* but unsafe to *generate*) falls through to
// the H3 console's own generation-time safety checker — a rejected/failed
// job there just surfaces as a normal "failed" queue entry.
const BANNED_WORDS = ["色情", "porn", "自杀", "血腥暴力", "毒品"];
function moderateText(text) {
  const lower = text.toLowerCase();
  const hit = BANNED_WORDS.find((w) => lower.includes(w));
  if (hit) return { ok: false, reason: `包含违禁词` };
  return { ok: true };
}

const CHAT_HISTORY_LIMIT = 300;
function pushChatMessage(msg) {
  chatMessages.push(msg);
  if (chatMessages.length > CHAT_HISTORY_LIMIT) chatMessages = chatMessages.slice(-CHAT_HISTORY_LIMIT);
}
function updateChatStatus(id, status) {
  const msg = chatMessages.find((m) => m.id === id);
  if (msg) msg.status = status;
}

// Shared by /api/chat (after moderation) and /api/prompt (direct API use,
// e.g. testing) — looks up a library match or kicks off generation, exactly
// like before chat existed. `nickname` is optional (empty for /api/prompt).
function submitPromptToQueue(id, prompt, nickname) {
  const entry = { id, prompt, nickname: nickname || null, submittedAt: Date.now(), votes: [] };
  const match = findLibraryMatch(normalizePrompt(prompt));
  if (match) {
    entry.status = "matched";
    entry.clip = match;
    promptQueue.push(entry);
    return { status: "matched", clip: match };
  }
  entry.status = "generating";
  promptQueue.push(entry);
  generateForPrompt(entry); // fire and forget — polled via /api/live/state
  return { status: "generating", id: entry.id };
}

function normalizePrompt(s) {
  return s.trim().toLowerCase().replace(/\s+/g, " ");
}
function findLibraryMatch(promptNorm) {
  return getLibrary().find((c) => {
    const zh = normalizePrompt(c.prompt);
    const en = c.promptEn ? normalizePrompt(c.promptEn) : null;
    return (
      zh === promptNorm ||
      zh.includes(promptNorm) ||
      promptNorm.includes(zh) ||
      (en && (en === promptNorm || en.includes(promptNorm) || promptNorm.includes(en)))
    );
  });
}

// Idle fallback pick avoids anything played within this window, so a clip
// that just aired doesn't come back around too soon. Falls back to ignoring
// the cooldown (keeping only the immediate-repeat guard) if literally
// everything is on cooldown, rather than ever stalling the schedule.
const REPEAT_COOLDOWN_MS = 20 * 60 * 1000;

function markPlayed(id) {
  const lib = getLibrary();
  const clip = lib.find((c) => c.id === id);
  if (!clip) return;
  clip.lastPlayedAt = Date.now();
  clip.playCount = (clip.playCount || 0) + 1;
  saveLibrary(lib);
}

// T36 (dev-plan-5.md): dance.html-only, deliberately not folded into the
// shared markPlayed() above — live.html's text-channel clips never have a
// user_paid character behind them, and keeping this explicit (called only
// from the two dance-specific scheduling call sites) matches
// architecture.md 2.1's "two independent product lines" rather than
// silently special-casing the shared helper. A clip's first play already
// happened via T34's priorityInbox insert ("确定性上镜"); every play after
// that — including this same clip recurring through the normal random-fill
// pool — keeps consuming the same purchased quota until it runs out.
function consumeCharacterSegment(clip) {
  if (!clip.characterId) return;
  const character = characters.get(clip.characterId);
  if (!character || character.source !== "user_paid" || character.status !== "active" || character.remainingSegments == null) return;
  const remainingSegments = Math.max(0, character.remainingSegments - 1);
  characters.update(character.id, { remainingSegments, status: remainingSegments === 0 ? "expired" : "active" });
}

// Consumed entries are spliced out immediately rather than left as
// status:"scheduled" — once a clip is in `schedule` it shows up via
// current/upNext, so keeping a second, never-cleared copy in promptQueue
// just grows forever and duplicates the same info.
// Returns {clip, requestedBy, chatId} — chatId lets the caller flip the
// originating chat message to "scheduled" once it's actually about to air.
// Among entries of the same status, the most-upvoted prompt goes first
// (ties broken by submission order) — lets chat bump a favorite to the
// front of the line instead of strict FIFO.
function voteCount(q) {
  return (q.votes || []).length;
}
// Shared by live's promptQueue and dance's freeQueue (T11) — takes the queue
// array as a param rather than closing over a module-scope variable so both
// channels' independent queues can use it.
function pickBestIndexByStatus(queue, status) {
  let bestIdx = -1;
  for (let i = 0; i < queue.length; i++) {
    const q = queue[i];
    if (q.status !== status) continue;
    if (bestIdx === -1) {
      bestIdx = i;
      continue;
    }
    const best = queue[bestIdx];
    if (voteCount(q) > voteCount(best)) bestIdx = i;
  }
  return bestIdx;
}
// Random-fill fallback shared by live's pickNextClip and dance's
// pickNextDanceClip (T11) — least-played-first within a cooldown-filtered
// pool, so idle filler time rotates evenly instead of a few clips dominating
// by chance. `pool` is caller-filtered (live excludes dance channel clips
// and vice versa, architecture.md 2.1: independent schedules per channel).
function pickLeastPlayedClip(pool, prevId) {
  if (!pool.length) return null;
  const notPrev = pool.length > 1 ? pool.filter((c) => c.id !== prevId) : pool;
  const now = Date.now();
  // Never-played clips (no lastPlayedAt) are always eligible — genuinely
  // random among everything that isn't on cooldown, no bias toward "fresh".
  const offCooldown = notPrev.filter((c) => !c.lastPlayedAt || now - c.lastPlayedAt > REPEAT_COOLDOWN_MS);
  const candidates = offCooldown.length ? offCooldown : notPrev;
  const minPlays = Math.min(...candidates.map((c) => c.playCount || 0));
  const leastPlayed = candidates.filter((c) => (c.playCount || 0) === minPlays);
  return leastPlayed[Math.floor(Math.random() * leastPlayed.length)];
}
function pickNextClip() {
  const readyIdx = pickBestIndexByStatus(promptQueue, "ready");
  if (readyIdx !== -1) {
    const q = promptQueue.splice(readyIdx, 1)[0];
    return { clip: q.clip, requestedBy: q.nickname, chatId: q.id };
  }
  const matchedIdx = pickBestIndexByStatus(promptQueue, "matched");
  if (matchedIdx !== -1) {
    const q = promptQueue.splice(matchedIdx, 1)[0];
    return { clip: q.clip, requestedBy: q.nickname, chatId: q.id };
  }

  // dance-channel clips (T8) don't belong in live.html's random filler pool
  // — the two channels keep independent schedules (architecture.md 2.1).
  const lib = getLibrary().filter((c) => c.channel !== "dance");
  if (!lib.length) return null;
  const prev = schedule.length ? schedule[schedule.length - 1].clip.id : null;
  const clip = pickLeastPlayedClip(lib, prev);
  return clip ? { clip, requestedBy: null, chatId: null } : null;
}

const FAILED_ENTRY_TTL_MS = 20000; // how long a "generation failed" entry stays visible before cleanup

function ensureSchedule() {
  const now = Date.now();
  while (schedule.length > 1 && schedule[1].endAt <= now) schedule.shift();
  while (schedule.length === 0 || schedule[schedule.length - 1].endAt < now + FILLER_DURATION_MS) {
    const picked = pickNextClip();
    if (!picked || !picked.clip) break;
    const { clip, requestedBy, chatId } = picked;
    markPlayed(clip.id);
    if (chatId) updateChatStatus(chatId, "scheduled");
    const startAt = schedule.length ? schedule[schedule.length - 1].endAt : now;
    schedule.push({ clip, startAt, endAt: startAt + clip.duration * 1000, requestedBy });
  }
  promptQueue = promptQueue.filter((q) => q.status !== "failed" || now - q.failedAt < FAILED_ENTRY_TTL_MS);

  for (const [cid, lastSeen] of viewers) if (now - lastSeen > VIEWER_TTL_MS) viewers.delete(cid);
  saveLiveState();
}
setInterval(ensureSchedule, SCHEDULE_TICK_MS);

// ---- viewer count: anyone whose /api/live/state poll landed in the last VIEWER_TTL_MS ----
const VIEWER_TTL_MS = 12000;
const viewers = new Map(); // clientId -> lastSeenAt
// dance.html keeps its own viewer count (T17), now one per room (getRoomViewers
// above) — every room's "在线人数" is independent, none of them summed together.
const danceViewers = new Map(); // characterId -> Map<clientId, lastSeenAt>

// ---- rate limiting: cheap per-IP throttle on prompt submission ----
const RATE_LIMIT_MAX = 3;
const RATE_LIMIT_WINDOW_MS = 5 * 60 * 1000;
const rateLimitHits = new Map(); // ip -> [timestamps]
function isRateLimited(ip) {
  const now = Date.now();
  const hits = (rateLimitHits.get(ip) || []).filter((t) => now - t < RATE_LIMIT_WINDOW_MS);
  hits.push(now);
  rateLimitHits.set(ip, hits);
  return hits.length > RATE_LIMIT_MAX;
}

// Runs in the background; never blocks the live schedule or the POST /api/prompt response.
// `entry.h3JobId` set (and persisted via saveLiveState) as soon as we have it,
// so a server restart mid-generation can resume polling instead of losing
// track of the job (see resumeGenerations() at startup).
async function generateForPrompt(entry) {
  try {
    if (!entry.h3JobId) {
      if (!entry.expandedPrompt) {
        entry.expandedPrompt = await optimizePrompt(entry.prompt);
        saveLiveState();
      }
      const submitted = await h3ConsoleFetch("/v1/videos", {
        method: "POST",
        body: { prompt: entry.expandedPrompt, ...H3_GEN_PARAMS },
      });
      if (!submitted.id) throw new Error(submitted.detail || "submit failed");
      entry.h3JobId = submitted.id;
      saveLiveState();
    }

    for (let i = 0; i < 120; i++) {
      await new Promise((r) => setTimeout(r, 5000));
      const job = await h3ConsoleFetch(`/v1/videos/${entry.h3JobId}`);
      if (job.deleted_at) throw new Error("job was deleted on the H3 console before it finished");
      if (job.status === "done") {
        const clip = {
          id: job.id,
          source: "h3console",
          prompt: entry.prompt,
          fullPrompt: entry.expandedPrompt || entry.prompt,
          width: job.req.width,
          height: job.req.height,
          duration: Math.round((job.req.frames / FPS) * 10) / 10,
          partition: job.partition,
          likes: 0,
          createdAt: Date.now(),
        };
        const lib = getLibrary();
        lib.push(clip);
        saveLibrary(lib);
        entry.status = "ready";
        entry.clip = clip;
        updateChatStatus(entry.id, "ready");
        saveLiveState();
        return;
      }
      if (job.status === "error" || job.status === "failed") throw new Error(job.error || "generation failed");
    }
    throw new Error("generation timed out");
  } catch (err) {
    entry.status = "failed";
    entry.error = err.message;
    entry.failedAt = Date.now();
    updateChatStatus(entry.id, "failed");
    saveLiveState();
  }
}

// Startup recovery: resume polling any generation that was mid-flight when
// the process last exited. Anything genuinely orphaned (no h3JobId — should
// never happen given the flow above) just gets dropped as failed.
function resumeGenerations() {
  for (const entry of promptQueue) {
    if (entry.status !== "generating") continue;
    if (entry.h3JobId) generateForPrompt(entry);
    else {
      entry.status = "failed";
      entry.error = "lost track of this generation across a restart";
      entry.failedAt = Date.now();
    }
  }
}

// ---- Dressup dance room: one-step generation orchestration (T8) ----
// Mirrors generateForPrompt's shape (submit -> persist h3JobId -> poll ->
// push a library.json clip on success) but for ref2va instead of plain
// text, and persisted in generationJobs (dressup-store.js) instead of
// live-state.json's promptQueue — this is an admin/batch-driven pipeline,
// not the viewer-facing live queue, so it shouldn't share that store.

// Forwards a store record's local upload to H3 Console's /v1/assets
// (S4 spike) the first time it's needed, then caches the result on the
// record so later generations reusing the same character/garment/dance-ref
// don't re-forward the same file (MVCP M.13).
async function ensureH3AssetUrl(store, record, localUrlField) {
  if (record.h3AssetUrl) return record.h3AssetUrl;
  const absPath = path.join(__dirname, record[localUrlField]);
  const asset = await forwardToH3Assets(absPath, H3_CONSOLE_BASE, H3_CONSOLE_TOKEN);
  store.update(record.id, { h3AssetUrl: asset.url });
  return asset.url;
}

// Same caching idea as ensureH3AssetUrl, separate field (fal is a
// completely different storage service, not interchangeable with
// h3AssetUrl — M.13's note that "S4 spike only solved the H3 Console side").
async function ensureFalAssetUrl(store, record, localUrlField) {
  if (record.falAssetUrl) return record.falAssetUrl;
  const absPath = path.join(__dirname, record[localUrlField]);
  const asset = await forwardToFalAssets(absPath, FAL_API_KEY, FAL_REST_BASE);
  store.update(record.id, { falAssetUrl: asset.url });
  return asset.url;
}

// T33: submit + poll + fetch-result against fal's queue API (verified
// contract, see FAL_MODEL_ID's doc comment above and forwardToFalAssets in
// uploads.js — POST {queueHost}/{model}, poll .../requests/{id}/status,
// fetch .../requests/{id}). Kept separate from h3ConsoleFetch's shape
// (single-poll-returns-everything) since fal's status/result are two
// different endpoints, not one.
async function falSubmit(input) {
  const res = await fetch(`${FAL_QUEUE_BASE}/${FAL_MODEL_ID}`, {
    method: "POST",
    headers: { Authorization: `Key ${FAL_API_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify(input),
  });
  const body = await res.json();
  if (!res.ok || !body.request_id) throw new Error(body.detail || body.error || `fal submit failed: ${res.status}`);
  return body; // { request_id, status_url, response_url, ... }
}
async function falPollStatus(requestId) {
  const res = await fetch(`${FAL_QUEUE_BASE}/${FAL_MODEL_ID}/requests/${requestId}/status`, {
    headers: { Authorization: `Key ${FAL_API_KEY}` },
  });
  return res.json(); // { status: "IN_QUEUE"|"IN_PROGRESS"|"COMPLETED"|... }
}
async function falFetchResult(requestId) {
  const res = await fetch(`${FAL_QUEUE_BASE}/${FAL_MODEL_ID}/requests/${requestId}`, {
    headers: { Authorization: `Key ${FAL_API_KEY}` },
  });
  const body = await res.json();
  if (!res.ok || !body.video || !body.video.url) throw new Error(body.detail || body.error || "fal result missing video.url");
  return body; // { video: { url, ... }, expanded_prompt }
}

// T39 (dev-plan-5.md; schema M.11) — operator hand-curated blocklist,
// distinct from T32's automated face-blacklist model and T26's garment
// moderation (see blacklist store's own doc comment, dressup-store.js).
function isBlacklisted(targetType, targetId) {
  if (!targetId) return false;
  return blacklist.list().some((b) => b.targetType === targetType && b.targetId === targetId);
}

function pickRefDanceVideo() {
  const pool = danceRefs.list().filter((d) => d.isActive);
  if (pool.length === 0) throw new Error("no active dance-refs available");
  return pool[Math.floor(Math.random() * pool.length)];
}

// 4.6 节去重缓存:相同 (characterId, garmentId) 组合直接复用已有产物。
// qcStatus:"incorrect" 的旧片段不算数——AI 质检没过的视频保留在库里(人物/衣服溯源、
// 问题说明都还在),只是不再被当成"已经生成过",这样纠错时重新提交就能真的再生成一条,
// 而不是又把去重缓存命中到那条坏的上面。
function findExistingGeneratedVideo(characterId, garmentId) {
  return getLibrary().find((c) => c.channel === "dance" && c.characterId === characterId && c.garmentId === garmentId && c.qcStatus !== "incorrect");
}

// Shared by the single-shot POST /api/admin/generate and the T9 batch
// endpoint: validates a (character, garment) pair, returns the cached clip
// if M.7's dedupe index already has one, otherwise queues a generationJobs
// record and fires generateDanceVideo (fire-and-forget — callers poll
// GET /api/admin/generate/:id or /api/admin/batch-gen/status for progress).
// Returns {status, body} so route handlers can just write it out.
// userId/priority (T33/T34, dev-plan-5.md): a free mode-一 pick passes
// neither (backend stays H3 Console, priority "normal"); T27 (mode 2)
// passes userId only (still "normal" — 需求文档 3 节: mode 2 stays in the
// vote-ranked queue, only mode 3 skips it); T35 (mode 3, once built) passes
// both userId and priority:"paid_boost".
function submitGeneration({ characterId, garmentId, refDanceVideoId, batchId, userId, priority }) {
  if (!characters.get(characterId) || !garments.get(garmentId)) {
    return { status: 400, body: { error: "characterId/garmentId must reference existing records" } };
  }
  const existing = findExistingGeneratedVideo(characterId, garmentId);
  if (existing) return { status: 200, body: { cached: true, clip: existing } };

  if (!refDanceVideoId) {
    try {
      refDanceVideoId = pickRefDanceVideo().id;
    } catch (err) {
      return { status: 400, body: { error: err.message } };
    }
  }
  // T33: paid requests (userId set) route to fal's real-time compute once
  // FAL_API_KEY is configured (需求文档 4.3 节双算力策略); everything else
  // — free mode-一, or a paid request before a key exists — stays on the
  // H3 Console path that's been working since T8.
  const backend = userId && FAL_API_KEY ? "fal" : "h3_console";
  const job = generationJobs.create({
    characterId,
    garmentId,
    refDanceVideoId,
    batchId: batchId || null,
    status: "queued",
    h3JobId: null,
    falRequestId: null,
    error: null,
    backend,
    userId: userId || null,
    priority: priority || "normal",
  });
  generateDanceVideo(job).catch(() => {});
  return { status: 200, body: { cached: false, jobId: job.id } };
}

// Dispatches on job.backend (T33) — H3 Console and fal.ai have genuinely
// different submit/poll/result shapes (see generateDanceVideoViaFal's doc
// comment), not just a different header, so this stays two implementations
// behind one entry point rather than one branchy function.
async function generateDanceVideo(job, opts = {}) {
  return job.backend === "fal" ? generateDanceVideoViaFal(job, opts) : generateDanceVideoViaH3(job, opts);
}

// job: a generationJobs record ({id, characterId, garmentId,
// refDanceVideoId, status, h3JobId, error, fullPrompt, backend, userId,
// priority}). Mutates it via generationJobs.update and keeps the local
// variable in sync (store.js has no in-memory cache, so every update is a
// fresh read-modify-write).
async function generateDanceVideoViaH3(job, opts = {}) {
  const pollIntervalMs = opts.pollIntervalMs || Number(process.env.GENERATION_POLL_INTERVAL_MS) || 5000;
  try {
    const character = characters.get(job.characterId);
    const garment = garments.get(job.garmentId);
    const danceRef = danceRefs.get(job.refDanceVideoId);
    if (!character || !garment || !danceRef) throw new Error("missing character/garment/dance-ref record");

    if (!job.h3JobId) {
      if (!job.fullPrompt) {
        const built = buildStage2Prompt({ character, garment, danceRef });
        job = generationJobs.update(job.id, { fullPrompt: built.prompt });
      }

      const [characterAssetUrl, garmentAssetUrl, danceRefAssetUrl] = await Promise.all([
        ensureH3AssetUrl(characters, character, "imageUrl"),
        ensureH3AssetUrl(garments, garment, "imageUrl"),
        ensureH3AssetUrl(danceRefs, danceRef, "videoUrl"),
      ]);

      const submitted = await h3ConsoleFetch("/v1/videos", {
        method: "POST",
        body: {
          prompt: job.fullPrompt,
          ...DANCE_GEN_PARAMS,
          reference_image_urls: [characterAssetUrl, garmentAssetUrl],
          reference_video_urls: [danceRefAssetUrl],
        },
      });
      if (!submitted.id) throw new Error(submitted.detail || "submit failed");
      job = generationJobs.update(job.id, { h3JobId: submitted.id, status: "generating" });
    }

    // ponytail: H3's 4 GPUs run one sharded model, not 4 independent
    // workers (H3-CONSOLE.md /v1/status), so a batch of N jobs is served
    // ~serially — the Nth job in queue_position can sit "queued" for
    // N * ~700s before it even starts. A fixed poll-count budget doesn't
    // know about queue depth, so this is wall-clock and generous instead;
    // upgrade path if batches grow past a couple dozen: read `eta_seconds`/
    // `queue_position` off the poll response and size the deadline to that.
    const deadline = Date.now() + (opts.timeoutMs || Number(process.env.GENERATION_TIMEOUT_MS) || 2 * 60 * 60 * 1000);
    while (Date.now() < deadline) {
      await new Promise((r) => setTimeout(r, pollIntervalMs));
      let polled;
      try {
        polled = await h3ConsoleFetch(`/v1/videos/${job.h3JobId}`);
      } catch {
        // A single bad poll (H3 Console hiccup — non-JSON 500 page, dropped
        // connection) isn't a generation failure; the job itself is still
        // fine on H3's side. Skip this tick and retry on the next one,
        // bounded by the same deadline as everything else. Confirmed live
        // 2026-09-02: a 20-job batch's concurrent polling briefly 500'd H3
        // Console, and every job got marked "failed" over a transient
        // response even though H3 still had them queued/running.
        continue;
      }
      if (polled.deleted_at) throw new Error("job was deleted on the H3 console before it finished");
      if (polled.status === "done") {
        const clip = {
          id: polled.id,
          source: "h3console",
          // ingest.js's syncLibrary() only carries an entry forward as-is
          // when `edited` is true — otherwise it rebuilds the record from
          // the raw H3 job on its next periodic sync, which knows nothing
          // about channel/characterId/garmentId/refDanceVideoId and would
          // silently strip them (and leak this clip into the non-dance
          // pickNextClip() pool, since `channel` would be gone too).
          edited: true,
          channel: "dance",
          characterId: job.characterId,
          garmentId: job.garmentId,
          refDanceVideoId: job.refDanceVideoId,
          backend: "h3_console",
          priority: job.priority || "normal",
          requestedByUserId: job.userId || null,
          prompt: `${character.name} × ${garment.name}`,
          fullPrompt: job.fullPrompt,
          width: polled.req.width,
          height: polled.req.height,
          duration: Math.round((polled.req.frames / FPS) * 10) / 10,
          partition: polled.partition,
          likes: 0,
          createdAt: Date.now(),
        };
        const lib = getLibrary();
        lib.push(clip);
        saveLibrary(lib);
        generationJobs.update(job.id, { status: "done", generatedVideoId: clip.id });
        return clip;
      }
      if (polled.status === "error" || polled.status === "failed" || polled.status === "cancelled") {
        throw new Error(polled.error || `generation ${polled.status}`);
      }
    }
    throw new Error("generation timed out");
  } catch (err) {
    generationJobs.update(job.id, { status: "failed", error: err.message });
    throw err;
  }
}

// T33: fal.ai's queue API — submit -> poll .../status -> once COMPLETED,
// fetch .../requests/{id} for the actual result (fal splits status and
// result into two endpoints; H3 Console's single poll returns both at
// once, see generateDanceVideoViaH3 above — genuinely different shapes,
// not just a header swap).
//
// NOT VERIFIED against a real fal account as of this commit — no
// FAL_API_KEY has ever been configured (dev-plan-5.md §1.2 item 2). The
// endpoints/params below come from fal's published docs and the fal-js
// client's own source (see forwardToFalAssets in uploads.js for
// citations), not guesswork — but whether the exact prompt text
// buildStage2Prompt produces (written for and verified against H3
// Console's <Picture N>/<Video N> convention) is interpreted the same way
// by minimax/h3/reference-to-video on fal is an open question (dev-plan-5.md
// §1.2 item 3) only a real call can answer. Also unverified: fal's
// terminal-failure status string(s) — the docs found only named IN_QUEUE/
// IN_PROGRESS/COMPLETED, so this deliberately does NOT guess an error
// enum; a failed fal job surfaces via the existing deadline timeout
// instead of a fast-fail, same conservative tradeoff as a transient poll
// hiccup below.
async function generateDanceVideoViaFal(job, opts = {}) {
  const pollIntervalMs = opts.pollIntervalMs || Number(process.env.GENERATION_POLL_INTERVAL_MS) || 5000;
  try {
    const character = characters.get(job.characterId);
    const garment = garments.get(job.garmentId);
    const danceRef = danceRefs.get(job.refDanceVideoId);
    if (!character || !garment || !danceRef) throw new Error("missing character/garment/dance-ref record");

    if (!job.falRequestId) {
      if (!job.fullPrompt) {
        const built = buildStage2Prompt({ character, garment, danceRef });
        job = generationJobs.update(job.id, { fullPrompt: built.prompt });
      }

      const [characterAssetUrl, garmentAssetUrl, danceRefAssetUrl] = await Promise.all([
        ensureFalAssetUrl(characters, character, "imageUrl"),
        ensureFalAssetUrl(garments, garment, "imageUrl"),
        ensureFalAssetUrl(danceRefs, danceRef, "videoUrl"),
      ]);

      const submitted = await falSubmit({
        prompt: job.fullPrompt,
        duration: 10, // seconds — fal's param is already in seconds, matching our fixed 10s default directly (no /24fps conversion like H3's `frames`)
        resolution: "480P",
        aspect_ratio: "9:16",
        reference_image_urls: [characterAssetUrl, garmentAssetUrl],
        reference_video_urls: [danceRefAssetUrl],
      });
      job = generationJobs.update(job.id, { falRequestId: submitted.request_id, status: "generating" });
    }

    const deadline = Date.now() + (opts.timeoutMs || Number(process.env.GENERATION_TIMEOUT_MS) || 2 * 60 * 60 * 1000);
    while (Date.now() < deadline) {
      await new Promise((r) => setTimeout(r, pollIntervalMs));
      let polled;
      try {
        polled = await falPollStatus(job.falRequestId);
      } catch {
        // Same reasoning as generateDanceVideoViaH3's poll try/catch: a
        // single bad poll isn't a generation failure, retry next tick.
        continue;
      }
      if (polled.status === "COMPLETED") {
        const result = await falFetchResult(job.falRequestId);
        const clip = {
          id: `fal-${job.falRequestId}`,
          source: "fal",
          // Already a public fal CDN URL — /lib/video/:id's existing
          // videoUrl branch (added for "manual" source clips) serves it
          // via redirect directly, no H3-style proxying needed.
          videoUrl: result.video.url,
          edited: true,
          channel: "dance",
          characterId: job.characterId,
          garmentId: job.garmentId,
          refDanceVideoId: job.refDanceVideoId,
          backend: "fal",
          priority: job.priority || "normal",
          requestedByUserId: job.userId || null,
          prompt: `${character.name} × ${garment.name}`,
          fullPrompt: job.fullPrompt,
          // fal's result schema (video.url/content_type/file_name/file_size)
          // doesn't echo back pixel dimensions the way H3 Console's `req`
          // does — these are what we *requested* via resolution/aspect_ratio,
          // not a confirmed readback.
          width: DANCE_GEN_PARAMS.width,
          height: DANCE_GEN_PARAMS.height,
          duration: 10,
          likes: 0,
          createdAt: Date.now(),
        };
        const lib = getLibrary();
        lib.push(clip);
        saveLibrary(lib);
        generationJobs.update(job.id, { status: "done", generatedVideoId: clip.id });
        return clip;
      }
    }
    throw new Error("generation timed out");
  } catch (err) {
    generationJobs.update(job.id, { status: "failed", error: err.message });
    throw err;
  }
}

// Startup recovery, same idea as resumeGenerations() but for generationJobs.
function resumeDressupGenerations() {
  for (const job of generationJobs.list()) {
    if (job.status !== "generating" && job.status !== "queued") continue;
    const inFlightId = job.backend === "fal" ? job.falRequestId : job.h3JobId;
    if (inFlightId) generateDanceVideo(job).catch(() => {});
    else generationJobs.update(job.id, { status: "failed", error: "lost track of this generation across a restart" });
  }
}

// ---- dance.html: one independent playout schedule + free (mode-一/衣柜)
// queue PER CHARACTER ROOM (T11, extended for multi-room 2026-09). Mirrors
// live's pickNextClip/ensureSchedule shape but everything takes the room
// object (getDanceRoom(characterId)) instead of closing over one global
// schedule/queue, and the random-fill pool is that character's own
// channel:"dance" clips only — no cross-character mixing.

// Shared by T34's priorityInbox drain and T39's admin "置顶下一条" pin —
// inserts right after whatever's currently playing (room.schedule[0]),
// pushing every later entry's timing back by this clip's duration rather
// than appending at the tail like the normal fill loop does.
function insertClipNext(room, clip, requestedBy, now) {
  const insertAt = room.schedule.length ? 1 : 0;
  const prevEndAt = insertAt > 0 ? room.schedule[insertAt - 1].endAt : now;
  room.schedule.splice(insertAt, 0, { videoId: clip.id, startAt: prevEndAt, endAt: prevEndAt + clip.duration * 1000, requestedBy: requestedBy || null });
  for (let i = insertAt + 1; i < room.schedule.length; i++) {
    room.schedule[i].startAt += clip.duration * 1000;
    room.schedule[i].endAt += clip.duration * 1000;
  }
}

// T39: admin "暂停自动填充" — freezes only the random-fill loop below (free
// mode-一 content competing for slots) for one room; priorityInbox
// (paid_boost) still drains immediately even while paused, matching
// 需求文档 6.5 节's own framing of "暂停自动填充" as a filler-specific
// control, not a full stop. Per-room set instead of one global flag, same
// reasoning as the schedule/queue split above.
let dancePausedRooms = new Set();

function pickNextDanceClip(characterId, room) {
  const readyIdx = pickBestIndexByStatus(room.queue, "ready");
  if (readyIdx !== -1) {
    const q = room.queue.splice(readyIdx, 1)[0];
    return { videoId: q.videoId, requestedBy: q.nickname };
  }
  // T39: a blacklisted generated_video/character/garment (M.11) is filtered
  // out of the candidate pool — "从排播候选和衣柜列表里过滤掉(不删除记录)".
  // T36's "expired user_paid character drops out of random-fill" is now a
  // whole-room early-exit in ensureRoomSchedule below instead of a per-clip
  // filter here, since the pool is already scoped to one character.
  const pool = getLibrary().filter((c) => {
    if (c.channel !== "dance" || c.characterId !== characterId) return false;
    if (c.qcStatus === "incorrect") return false; // AI 质检没过的片段不进直播间排播候选,但保留在库里
    if (!c.published) return false; // 2026-09 上架/下架: only published clips fill the room on their own
    if (isBlacklisted("generated_video", c.id)) return false;
    if (c.garmentId && isBlacklisted("garment", c.garmentId)) return false;
    return true;
  });
  if (!pool.length) return null;
  const prevVideoId = room.schedule.length ? room.schedule[room.schedule.length - 1].videoId : null;
  const clip = pickLeastPlayedClip(pool, prevVideoId);
  return clip ? { videoId: clip.id, requestedBy: null } : null;
}

function ensureRoomSchedule(characterId, now) {
  const room = getDanceRoom(characterId);
  const character = characters.get(characterId);
  if (isBlacklisted("character", characterId)) return; // T39: blacklisted character's room just stops advancing

  // Reconcile in-flight picks against generationJobs — the store, not an
  // in-memory promise, is the source of truth (T8's resumeDressupGenerations
  // already re-polls H3 for jobs still running after a restart; this tick
  // just needs to notice when they land, restart or not).
  // T34: a paid_boost job landing here gets diverted to priorityInbox
  // instead of "ready" (which would otherwise route it through
  // pickBestIndexByStatus's vote-ranked pick below) — collected here and
  // spliced out of room.queue after the loop rather than mid-iteration,
  // since room.queue is being iterated live.
  const divertedToPriorityInbox = [];
  for (const q of room.queue) {
    if (q.status !== "generating" || !q.jobId) continue;
    const job = generationJobs.get(q.jobId);
    if (!job) continue;
    if (job.status === "done") {
      if (job.priority === "paid_boost") {
        room.priorityInbox.push({ videoId: job.generatedVideoId, requestedBy: q.nickname || null });
        divertedToPriorityInbox.push(q);
      } else {
        q.status = "ready";
        q.videoId = job.generatedVideoId;
      }
    } else if (job.status === "failed") {
      q.status = "failed";
      q.error = job.error;
      q.failedAt = now;
      // T27's paid path (userId/amountPaid only set there — free mode-一
      // picks have neither): refund on generation failure, per "共同后置
      // 流程"'s stated floor. Guarded by an existing-refund lookup rather
      // than trusting this branch only ever runs once — it normally does
      // (room.queue entries only transition "generating" -> "failed" a
      // single time, this loop's own `q.status !== "generating"` guard
      // above prevents re-entry), but a crash between this write and
      // saveDanceState() persisting it could in principle replay the same
      // transition once after restart, and a duplicate refund is real
      // money, not a cosmetic bug.
      if (q.userId && q.amountPaid) {
        const alreadyRefunded = creditLedger.findByRelatedAssetAndReason(q.garmentId, "refund_stage2_fail").length > 0;
        if (!alreadyRefunded) {
          try {
            creditLedger.refund({ userId: q.userId, amount: q.amountPaid, reason: "refund_stage2_fail", relatedAssetId: q.garmentId });
          } catch (err) {
            // NO_SUCH_USER (deleted account) is the only realistic failure
            // here — refund only ever adds, so it can't hit
            // INSUFFICIENT_BALANCE. This branch won't be revisited (the
            // guard above only enters on "generating" -> "failed", a
            // one-time transition), so this is a genuine miss, not a
            // deferred retry — logged rather than silently dropped.
            console.error(`[refund_stage2_fail] failed to refund userId=${q.userId} garmentId=${q.garmentId}: ${err.message}`);
          }
        }
      }
    }
  }

  while (room.schedule.length > 1 && room.schedule[1].endAt <= now) room.schedule.shift();

  // T34: paid_boost content must play "next" (需求文档 3 节: "确定性上镜"),
  // not just "whenever the 30s-ahead fill horizon next needs topping up" —
  // if the schedule is already pre-filled (common: FILLER_DURATION_MS keeps
  // ~30s queued), the fill loop below wouldn't run again for a while and a
  // ready priorityInbox entry could sit for a long time. So this inserts
  // eagerly, right after whatever's currently playing (room.schedule[0],
  // guaranteed accurate now that expired entries were just shifted out
  // above), pushing every later entry's timing back by this clip's
  // duration rather than waiting for its "natural" turn.
  while (room.priorityInbox.length) {
    const next = room.priorityInbox.shift();
    const clip = getLibrary().find((c) => c.id === next.videoId);
    if (!clip) continue; // stale/removed videoId — drop rather than schedule a dead entry
    markPlayed(clip.id);
    consumeCharacterSegment(clip);
    insertClipNext(room, clip, next.requestedBy, now);
  }

  // T36: a user_paid character whose purchased segments have all played
  // (status:"expired") stops random-filling its room entirely — the record
  // and its videos stay in library.json (M.3/M.7: "记录保留"), the room
  // just goes quiet on whatever's left in schedule/priorityInbox.
  const roomExpired = character && character.status === "expired";
  while (!roomExpired && !dancePausedRooms.has(characterId) && (room.schedule.length === 0 || room.schedule[room.schedule.length - 1].endAt < now + FILLER_DURATION_MS)) {
    const picked = pickNextDanceClip(characterId, room);
    if (!picked || !picked.videoId) break;
    const clip = getLibrary().find((c) => c.id === picked.videoId);
    if (!clip) break; // stale/removed videoId — guard rather than schedule a dead entry
    markPlayed(clip.id);
    consumeCharacterSegment(clip);
    const startAt = room.schedule.length ? room.schedule[room.schedule.length - 1].endAt : now;
    room.schedule.push({ videoId: picked.videoId, startAt, endAt: startAt + clip.duration * 1000, requestedBy: picked.requestedBy });
  }
  room.queue = room.queue.filter((q) => !divertedToPriorityInbox.includes(q) && (q.status !== "failed" || now - q.failedAt < FAILED_ENTRY_TTL_MS));

  const viewerMap = getRoomViewers(characterId);
  for (const [cid, lastSeen] of viewerMap) if (now - lastSeen > VIEWER_TTL_MS) viewerMap.delete(cid);
}

function ensureDanceSchedule() {
  const now = Date.now();
  for (const characterId of getDanceRoomCharacterIds()) ensureRoomSchedule(characterId, now);
  saveDanceState();
}
setInterval(ensureDanceSchedule, SCHEDULE_TICK_MS);

http
  .createServer((req, res) => {
    if (req.url.startsWith("/fal/")) {
      const proxyReq = https.request(
        {
          hostname: FAL_HOST,
          path: req.url.slice(4),
          method: req.method,
          headers: { ...req.headers, host: FAL_HOST },
        },
        (proxyRes) => {
          res.writeHead(proxyRes.statusCode, proxyRes.headers);
          proxyRes.pipe(res);
        }
      );
      proxyReq.on("error", (err) => {
        res.writeHead(502, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: { message: err.message } }));
      });
      req.pipe(proxyReq);
      return;
    }

    const pathname = req.url.split("?")[0];

    if (pathname === "/api/admin/login" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          if (!ADMIN_PASSWORD || body.password !== ADMIN_PASSWORD) {
            res.writeHead(401, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "invalid password" }));
            return;
          }
          const token = crypto.randomUUID();
          adminSessions.set(token, Date.now() + ADMIN_SESSION_TTL_MS);
          res.writeHead(200, {
            "Content-Type": "application/json",
            "Set-Cookie": `${ADMIN_SESSION_COOKIE}=${token}; HttpOnly; Path=/; Max-Age=${Math.floor(ADMIN_SESSION_TTL_MS / 1000)}; SameSite=Lax`,
          });
          res.end(JSON.stringify({ ok: true }));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    if (pathname === "/api/admin/logout" && req.method === "POST") {
      const token = parseCookies(req)[ADMIN_SESSION_COOKIE];
      if (token) adminSessions.delete(token);
      res.writeHead(200, {
        "Content-Type": "application/json",
        "Set-Cookie": `${ADMIN_SESSION_COOKIE}=; HttpOnly; Path=/; Max-Age=0`,
      });
      res.end(JSON.stringify({ ok: true }));
      return;
    }

    // Viewer account auth (dev-plan-3.md T19) — entirely separate from the
    // /api/admin/* gate right below. Registering/logging in is always
    // optional: /api/dance/* keeps working on the plain viewer_uid cookie
    // with no session at all (see requireUserSession's doc comment).
    if (pathname === "/api/auth/register" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          const email = (body.email || "").trim().toLowerCase();
          const password = body.password || "";
          if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "invalid email" }));
            return;
          }
          if (password.length < 8) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "password must be at least 8 characters" }));
            return;
          }
          // T21: an existing anonymous viewer_uid/viewer_nickname cookie
          // (set client-side by live.html/dance.html, plaintext, never
          // trusted for anything sensitive) gets carried onto the new
          // account — history isn't rewritten, but future votes/plays from
          // this browser stay attributed to the same identity.
          const existingCookies = parseCookies(req);
          let user;
          try {
            user = userStore.create({
              email,
              passwordHash: hashPassword(password),
              nickname: existingCookies.viewer_nickname || null,
              legacyUid: existingCookies.viewer_uid || null,
            });
          } catch (err) {
            if (err.code === "EMAIL_TAKEN") {
              res.writeHead(409, { "Content-Type": "application/json" });
              res.end(JSON.stringify({ error: "email already registered" }));
              return;
            }
            throw err;
          }
          const session = userSessions.create({ userId: user.id, kind: "session", expiresAt: Date.now() + USER_SESSION_TTL_MS });
          // T20: fire off the verification email. sendVerificationEmail is
          // the entire integration seam — see its own comment.
          const verifySession = userSessions.create({ userId: user.id, kind: "email_verify", expiresAt: Date.now() + EMAIL_VERIFY_TTL_MS });
          const devVerifyUrl = sendVerificationEmail(user.email, verifySession.token);
          const responseBody = { id: user.id, email: user.email, emailVerified: user.emailVerified, nickname: user.nickname };
          if (process.env.NODE_ENV !== "production") responseBody.devVerifyUrl = devVerifyUrl;
          res.writeHead(200, {
            "Content-Type": "application/json",
            "Set-Cookie": `${USER_SESSION_COOKIE}=${session.token}; HttpOnly; Path=/; Max-Age=${Math.floor(USER_SESSION_TTL_MS / 1000)}; SameSite=Lax`,
          });
          res.end(JSON.stringify(responseBody));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    if (pathname === "/api/auth/login" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          const email = (body.email || "").trim().toLowerCase();
          const password = body.password || "";
          const user = userStore.findByEmail(email);
          // Deliberately the same error for "no such email" and "wrong
          // password" — distinguishing the two lets an attacker enumerate
          // which emails are registered.
          if (!user || !verifyPassword(password, user.passwordHash)) {
            res.writeHead(401, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "invalid email or password" }));
            return;
          }
          const session = userSessions.create({ userId: user.id, kind: "session", expiresAt: Date.now() + USER_SESSION_TTL_MS });
          const setCookies = [`${USER_SESSION_COOKIE}=${session.token}; HttpOnly; Path=/; Max-Age=${Math.floor(USER_SESSION_TTL_MS / 1000)}; SameSite=Lax`];
          // T21: push the account's bound identity back onto this browser,
          // even if it showed up with no viewer_uid cookie at all or a
          // fresh one from a different device — otherwise logging in from
          // a clean browser would silently start a new anonymous identity,
          // which for anything vote-limited defeats the point of binding
          // it to an account in the first place.
          if (user.legacyUid) setCookies.push(viewerIdentityCookie("viewer_uid", user.legacyUid));
          if (user.nickname) setCookies.push(viewerIdentityCookie("viewer_nickname", user.nickname));
          res.writeHead(200, { "Content-Type": "application/json", "Set-Cookie": setCookies });
          res.end(JSON.stringify({ id: user.id, email: user.email, emailVerified: user.emailVerified, nickname: user.nickname }));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    // T20: single-use — the email_verify session is revoked on success, so
    // a second visit to the same link (or an expired one) hits the same
    // "invalid or expired" error rather than silently re-succeeding.
    if (pathname === "/api/auth/verify" && req.method === "GET") {
      const params = new URLSearchParams(req.url.split("?")[1] || "");
      const token = params.get("token") || "";
      const verifySession = userSessions.findByToken(token);
      if (!verifySession || verifySession.kind !== "email_verify") {
        res.writeHead(400, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "invalid or expired verification link" }));
        return;
      }
      userStore.update(verifySession.userId, { emailVerified: true });
      userSessions.revoke(token);
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ ok: true }));
      return;
    }

    if (pathname === "/api/auth/logout" && req.method === "POST") {
      const token = parseCookies(req)[USER_SESSION_COOKIE];
      if (token) userSessions.revoke(token);
      res.writeHead(200, {
        "Content-Type": "application/json",
        "Set-Cookie": `${USER_SESSION_COOKIE}=; HttpOnly; Path=/; Max-Age=0`,
      });
      res.end(JSON.stringify({ ok: true }));
      return;
    }

    // Debug-only endpoint, per T19's own acceptance criteria — fine to
    // keep past this task too (a real account page will want it), but
    // intentionally minimal for now.
    if (pathname === "/api/auth/me" && req.method === "GET") {
      const user = requireUserSession(req);
      if (!user) {
        res.writeHead(401, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "unauthorized" }));
        return;
      }
      res.writeHead(200, { "Content-Type": "application/json" });
      // creditBalance riding along here (T29) rather than a dedicated
      // /api/credits/balance endpoint — it's the same "logged-in user's own
      // state" this route already exists to serve, and refreshAuthState()
      // in live.html/dance.html (T22) already polls this after every login.
      res.end(JSON.stringify({ id: user.id, email: user.email, emailVerified: user.emailVerified, nickname: user.nickname, creditBalance: user.creditBalance }));
      return;
    }

    // T24: credit topup. Login + emailVerified matches M.10's "任何扣积分/
    // 写用户资产的接口" rule — a topup adds money rather than spending it,
    // but still needs an accountable identity before a real charge runs.
    if (pathname === "/api/credits/checkout" && req.method === "POST") {
      const user = requireUserSession(req);
      if (!user) {
        res.writeHead(401, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "login required" }));
        return;
      }
      if (!user.emailVerified) {
        res.writeHead(403, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "email verification required before purchasing credits" }));
        return;
      }
      readJsonBody(req)
        .then(async (body) => {
          try {
            const session = await createCheckoutSession({ userId: user.id, tierKey: (body.tierKey || "").trim() });
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(JSON.stringify(session));
          } catch (err) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: err.message }));
          }
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    // Dev-only completion of a mock checkout created above — simulates the
    // browser landing back from Stripe's hosted page after a successful
    // payment. Only ever reachable via a token this same process handed
    // out (createMockCheckoutUrl), so there's nothing to authenticate here
    // beyond "does this token exist and is it unused."
    if (pathname === "/api/credits/mock-checkout" && req.method === "GET") {
      const token = new URL(req.url, "http://x").searchParams.get("token") || "";
      const pending = pendingMockCheckouts.get(token);
      pendingMockCheckouts.delete(token); // single-use, same spirit as T20's email-verify tokens
      if (!pending || pending.expiresAt < Date.now()) {
        res.writeHead(400, { "Content-Type": "text/plain" });
        res.end("invalid or expired mock checkout token");
        return;
      }
      try {
        completeTopup({ userId: pending.userId, tierKey: pending.tierKey, paymentRef: `mock_${token}` });
        res.writeHead(302, { Location: "/dance.html?topup=success" });
        res.end();
      } catch (err) {
        res.writeHead(400, { "Content-Type": "text/plain" });
        res.end(err.message);
      }
      return;
    }

    // Real Stripe webhook — only meaningful once a real
    // STRIPE_WEBHOOK_SECRET is configured (tomorrow, per the user).
    // Refuses anything it can't verify rather than trusting an
    // unsigned/unverifiable request, even before a secret exists
    // (dev-plan-4.md T24's explicit acceptance criterion).
    if (pathname === "/api/credits/webhook" && req.method === "POST") {
      readRawTextBody(req)
        .then((rawBody) => {
          if (!STRIPE_WEBHOOK_SECRET || !verifyStripeWebhookSignature(rawBody, req.headers["stripe-signature"], STRIPE_WEBHOOK_SECRET)) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "signature verification failed" }));
            return;
          }
          let event;
          try {
            event = JSON.parse(rawBody);
          } catch {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "invalid JSON" }));
            return;
          }
          if (event.type === "checkout.session.completed") {
            const session = event.data.object;
            try {
              // event.id, not session.id: Stripe's at-least-once
              // redelivery resends the same event id for the same
              // occurrence, which is exactly what topup()'s paymentRef
              // dedup (db.js) keys on.
              completeTopup({ userId: session.metadata.userId, tierKey: session.metadata.tierKey, paymentRef: event.id });
            } catch (err) {
              // Already-applied duplicates are handled inside topup()
              // itself (returns the existing row, doesn't throw) — a throw
              // here means something genuinely went wrong (unknown tier,
              // missing user), not a benign redelivery.
              res.writeHead(400, { "Content-Type": "application/json" });
              res.end(JSON.stringify({ error: err.message }));
              return;
            }
          }
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ received: true }));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "failed to read request body" }));
        });
      return;
    }

    if (pathname.startsWith("/api/admin/") && !isAdminAuthed(req)) {
      res.writeHead(401, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ error: "unauthorized" }));
      return;
    }

    if (charactersCrud(pathname, req, res)) return;
    if (characterImagesCrud(pathname, req, res)) return;
    if (garmentsCrud(pathname, req, res)) return;
    if (danceRefsCrud(pathname, req, res)) return;

    // Standalone "人衣图生成" admin tool (admin-dressgen.html +
    // admin-dressgen-task.html): up to 6 person reference photos
    // (full-body/face × front/side/back, however many are actually
    // uploaded) + 1 garment image (a) -> 3 new full-body images of that
    // person wearing the garment, one per view (c), generated by 3
    // sequential gpt-image-2 calls. This is a real background task, not a
    // blocking request: POST creates the row (status "queued") and returns
    // its id immediately, then runDressGenViews() runs fire-and-forget —
    // the 3 upstream calls take ~70s+ each (CODEX-IMAGEGEN.md), so blocking
    // the HTTP response on all 3 sequentially risked a front-end proxy
    // timing the request out (a real 502 was hit doing exactly this before
    // this was made async). The client polls GET /dressgen (list) or
    // GET /dressgen/:id (task detail) to watch it progress. See
    // generateDressImage()'s doc comment for the vendor contract this
    // assumes, and DRESSGEN_PERSON_SLOTS above for why one call gets every
    // uploaded person image rather than a fixed per-view pairing.
    if (pathname === "/api/admin/dressgen/prompts" && req.method === "GET") {
      const prompts = {};
      DRESSGEN_VIEWS.forEach((view) => (prompts[view] = defaultDressgenPrompt(view)));
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(prompts));
      return;
    }
    if (pathname === "/api/admin/dressgen" && req.method === "GET") {
      // Paginated (2026-09-03) — store.list()/dress-gen.json is a
      // full-file read (store.js's own doc comment), fine today at a
      // handful of records but not something to keep shipping whole to
      // the browser as it grows. Newest-first, same order the frontend
      // used to produce itself via .slice().reverse().
      const params = new URL(req.url, "http://x").searchParams;
      const page = Math.max(1, Number(params.get("page")) || 1);
      const pageSize = Math.min(100, Math.max(1, Number(params.get("pageSize")) || 20));
      const all = dressGenRecords.list().slice().reverse();
      const items = all.slice((page - 1) * pageSize, page * pageSize);
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ items, total: all.length, page, pageSize }));
      return;
    }
    if (pathname === "/api/admin/dressgen" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          if (typeof body.garmentImage !== "string" || !body.garmentImage.startsWith("/uploads/")) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "garmentImage must be a /uploads/... path from POST /api/admin/upload" }));
            return;
          }
          const providedPersonSlots = DRESSGEN_PERSON_SLOTS.filter((f) => typeof body[f] === "string" && body[f]);
          const badSlot = providedPersonSlots.find((f) => !body[f].startsWith("/uploads/"));
          if (badSlot) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: `${badSlot} must be a /uploads/... path from POST /api/admin/upload` }));
            return;
          }
          if (providedPersonSlots.length === 0) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "at least one person reference image is required (upload as many of the 6 as you have)" }));
            return;
          }
          const provider = DRESSGEN_PROVIDERS.includes(body.provider) ? body.provider : DRESSGEN_DEFAULT_PROVIDER;
          const missingKey = dressGenProviderKeyMissing(provider);
          if (missingKey) {
            res.writeHead(500, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: missingKey }));
            return;
          }

          const prompts = {};
          for (const view of DRESSGEN_VIEWS) {
            const custom = body.prompts && typeof body.prompts[view] === "string" ? body.prompts[view].trim() : "";
            prompts[view] = custom || defaultDressgenPrompt(view);
          }

          const record = { garmentImage: body.garmentImage, prompts, provider };
          for (const slot of DRESSGEN_PERSON_SLOTS) record[slot] = body[slot] || null;
          record.status = "queued";
          record.viewStatus = { front: "queued", side: "queued", back: "queued" };
          record.outputImages = { front: null, side: null, back: null };
          record.errors = { front: null, side: null, back: null };
          record.viewProvider = { front: null, side: null, back: null };

          const entry = dressGenRecords.create(record);
          runDressGenViews(entry.id, dressGenImageAbsPaths(entry), DRESSGEN_VIEWS).catch(() => {});
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(entry));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }
    // Retry: reuses the row's own stored images/prompts — no re-upload, no
    // re-typing a prompt (that was an explicit ask: a failed task should be
    // re-runnable with one click). Whole-task retry only reprocesses views
    // that don't already have an output (so a "partial" task doesn't redo
    // the view(s) that already succeeded); per-view retry
    // (POST .../:id/retry/:view) reprocesses exactly the one view clicked,
    // for admin-dressgen-task.html's "regenerate just this image" button.
    if (/^\/api\/admin\/dressgen\/[^/]+\/retry\/(front|side|back)$/.test(pathname) && req.method === "POST") {
      const [, id, view] = pathname.match(/^\/api\/admin\/dressgen\/([^/]+)\/retry\/(front|side|back)$/);
      const record = dressGenRecords.get(id);
      if (!record) {
        res.writeHead(404, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "not found" }));
        return;
      }
      readJsonBody(req)
        .catch(() => ({})) // an empty/absent body is fine — retry with the stored prompt/provider as-is
        .then((body) => {
          // admin-dressgen-task.html's per-image "edit prompt then
          // regenerate" flow: an optional prompt override for just this
          // view, persisted so the record keeps reflecting what was
          // actually sent. Same for an optional provider override — e.g.
          // switching a view that failed on image2 over to wavespeed
          // instead, an explicit admin choice per the note above
          // generateDressImage, not an automatic fallback.
          const promptOverride = typeof body.prompt === "string" && body.prompt.trim() ? body.prompt.trim() : null;
          const provider = DRESSGEN_PROVIDERS.includes(body.provider) ? body.provider : record.provider || DRESSGEN_DEFAULT_PROVIDER;
          const missingKey = dressGenProviderKeyMissing(provider);
          if (missingKey) {
            res.writeHead(500, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: missingKey }));
            return;
          }
          const updated = dressGenRecords.update(id, {
            status: "generating",
            provider,
            viewStatus: { ...record.viewStatus, [view]: "queued" },
            prompts: promptOverride ? { ...record.prompts, [view]: promptOverride } : record.prompts,
          });
          runDressGenViews(id, dressGenImageAbsPaths(updated), [view]).catch(() => {});
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(updated));
        });
      return;
    }
    if (/^\/api\/admin\/dressgen\/[^/]+\/retry$/.test(pathname) && req.method === "POST") {
      const id = pathname.slice("/api/admin/dressgen/".length, -"/retry".length);
      const record = dressGenRecords.get(id);
      if (!record) {
        res.writeHead(404, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "not found" }));
        return;
      }
      readJsonBody(req)
        .catch(() => ({})) // an empty/absent body is fine — retry with the stored provider as-is
        .then((body) => {
          // Optional provider override, same as per-view retry above — an
          // explicit admin choice (e.g. image2 failed, switch to
          // wavespeed), not an automatic fallback.
          const provider = DRESSGEN_PROVIDERS.includes(body.provider) ? body.provider : record.provider || DRESSGEN_DEFAULT_PROVIDER;
          const missingKey = dressGenProviderKeyMissing(provider);
          if (missingKey) {
            res.writeHead(500, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: missingKey }));
            return;
          }
          const viewsToRetry = DRESSGEN_VIEWS.filter((v) => !record.outputImages[v]);
          if (viewsToRetry.length === 0) {
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(JSON.stringify(record)); // already fully done — nothing to retry
            return;
          }
          const viewStatus = { ...record.viewStatus };
          viewsToRetry.forEach((v) => (viewStatus[v] = "queued"));
          const updated = dressGenRecords.update(id, { status: "generating", provider, viewStatus });
          runDressGenViews(id, dressGenImageAbsPaths(updated), viewsToRetry).catch(() => {});
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(updated));
        });
      return;
    }
    if (pathname.startsWith("/api/admin/dressgen/") && req.method === "DELETE") {
      const removed = dressGenRecords.remove(pathname.slice("/api/admin/dressgen/".length));
      res.writeHead(removed ? 200 : 404, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ deleted: removed }));
      return;
    }
    if (pathname.startsWith("/api/admin/dressgen/") && req.method === "GET") {
      const record = dressGenRecords.get(pathname.slice("/api/admin/dressgen/".length));
      res.writeHead(record ? 200 : 404, { "Content-Type": "application/json" });
      res.end(JSON.stringify(record || { error: "not found" }));
      return;
    }

    // T30: manual balance correction, e.g. a support gesture ("sorry about
    // the failed generation that didn't auto-refund, here's some credits")
    // or clawing back an abused promo. Always attributable — see
    // adminActorUserId's doc comment.
    if (pathname === "/api/admin/credit/adjust" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          const userId = (body.userId || "").trim();
          const delta = Number(body.delta);
          if (!userId || !userStore.get(userId) || !Number.isFinite(delta) || delta === 0) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "userId (must reference an existing user) and a non-zero numeric delta are required" }));
            return;
          }
          try {
            const row = creditLedger.adjust({ userId, delta, reason: (body.reason || "admin_adjust").trim(), actorUserId: adminActorUserId(req) });
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(JSON.stringify(row));
          } catch (err) {
            const status = err.code === "INSUFFICIENT_BALANCE" ? 400 : 500;
            res.writeHead(status, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: err.message }));
          }
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    // T39 (M.11): 运营手工拉黑. 拦截点在提交类接口自身
    // (/api/dance/pick、两个 upload——见各自的 isBlacklisted 调用),这里
    // 只是维护这张表.
    if (pathname === "/api/admin/blacklist" && req.method === "GET") {
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(blacklist.list()));
      return;
    }
    if (pathname === "/api/admin/blacklist" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          const targetType = (body.targetType || "").trim();
          const targetId = (body.targetId || "").trim();
          const validTypes = ["user", "character", "garment", "generated_video", "ip"];
          if (!validTypes.includes(targetType) || !targetId) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: `targetType must be one of ${validTypes.join("/")}, targetId is required` }));
            return;
          }
          const entry = blacklist.create({ targetType, targetId, reason: (body.reason || "").trim(), createdBy: adminActorUserId(req) });
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(entry));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }
    if (pathname.startsWith("/api/admin/blacklist/") && req.method === "DELETE") {
      const removed = blacklist.remove(pathname.slice("/api/admin/blacklist/".length));
      res.writeHead(removed ? 200 : 404, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ deleted: removed }));
      return;
    }

    // T39 (需求文档 6.5 节): dance.html 播放管理——插播/置顶、跳过当前、
    // 暂停/恢复自动填充.
    if (pathname === "/api/admin/dance/schedule/pin" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          const clip = getLibrary().find((c) => c.id === body.videoId && c.channel === "dance");
          if (!clip || !clip.characterId) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "videoId must reference an existing dance clip with a character (a room to pin it into)" }));
            return;
          }
          ensureDanceSchedule(); // settle any pending state before splicing
          const room = getDanceRoom(clip.characterId);
          insertClipNext(room, clip, "管理员置顶", Date.now());
          saveDanceState();
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ ok: true, characterId: clip.characterId, schedule: room.schedule }));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }
    if (pathname === "/api/admin/dance/schedule/skip" && req.method === "POST") {
      const characterId = new URL(req.url, "http://x").searchParams.get("characterId");
      if (!characterId || !characters.get(characterId)) {
        res.writeHead(400, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "characterId query param must reference an existing character" }));
        return;
      }
      ensureDanceSchedule();
      const room = getDanceRoom(characterId);
      if (room.schedule.length > 1) {
        room.schedule.shift(); // next tick's own "shift expired entries" step will pick up the new current from here
      } else if (room.schedule.length === 1) {
        room.schedule[0].endAt = Date.now(); // nothing queued behind it — force it to expire now, next tick fills a replacement
      }
      ensureDanceSchedule(); // fill immediately rather than waiting up to SCHEDULE_TICK_MS
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ ok: true, schedule: room.schedule }));
      return;
    }
    if (pathname === "/api/admin/dance/pause" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          if (!body.characterId || !characters.get(body.characterId)) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "characterId must reference an existing character" }));
            return;
          }
          if (body.paused) dancePausedRooms.add(body.characterId);
          else dancePausedRooms.delete(body.characterId);
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ characterId: body.characterId, paused: dancePausedRooms.has(body.characterId) }));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    if (pathname === "/api/admin/generate" && req.method === "GET") {
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(generationJobs.list()));
      return;
    }

    if (pathname === "/api/admin/generate" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          const { status, body: respBody } = submitGeneration(body);
          res.writeHead(status, { "Content-Type": "application/json" });
          res.end(JSON.stringify(respBody));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    if (pathname.startsWith("/api/admin/generate/") && req.method === "GET") {
      const job = generationJobs.get(pathname.slice("/api/admin/generate/".length));
      if (!job) {
        res.writeHead(404, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "not found" }));
        return;
      }
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(job));
      return;
    }

    // T9 冷启动批量生成:{characterId, garmentIds[], refDanceVideoIds?[]}.
    // No refDanceVideoIds given -> one job per garment, each with its own
    // random active dance-ref (same as the single-generate default).
    // refDanceVideoIds given -> full garmentIds x refDanceVideoIds cross
    // product, so an operator can pin specific reference dances.
    // Every combo goes through submitGeneration, so the M.7 dedupe cache
    // (same characterId+garmentId already generated) is honored per combo,
    // not just per batch.
    if (pathname === "/api/admin/batch-gen" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          const { characterId, garmentIds, refDanceVideoIds } = body;
          if (!characters.get(characterId) || !Array.isArray(garmentIds) || garmentIds.length === 0) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "characterId must exist and garmentIds must be a non-empty array" }));
            return;
          }
          const batchId = crypto.randomUUID();
          const refCombos = Array.isArray(refDanceVideoIds) && refDanceVideoIds.length > 0 ? refDanceVideoIds : [undefined];
          const results = [];
          for (const garmentId of garmentIds) {
            for (const refDanceVideoId of refCombos) {
              const { status, body: respBody } = submitGeneration({ characterId, garmentId, refDanceVideoId, batchId });
              results.push({ garmentId, refDanceVideoId: refDanceVideoId || null, status, ...respBody });
            }
          }
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ batchId, results }));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    if (pathname === "/api/admin/batch-gen/status" && req.method === "GET") {
      const batchId = new URL(req.url, "http://x").searchParams.get("batchId");
      if (!batchId) {
        res.writeHead(400, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "batchId query param required" }));
        return;
      }
      const jobs = generationJobs.list().filter((j) => j.batchId === batchId);
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(jobs));
      return;
    }

    // ---- dance.html: public viewer-facing endpoints (T11/T12/T15/T17) ----
    // No admin auth (T6 only gates /api/admin/*) — these are the free,
    // anonymous, 模式一 (衣柜选衣服) path. 模式二/三 (T27/T35, below) each
    // require login+emailVerified on their own.

    // One live room per character (2026-09): a room exists for every
    // character with >=1 generated dance video — no separate publish
    // toggle. Room list page polls this for its "直播间列表".
    if (pathname === "/api/dance/rooms" && req.method === "GET") {
      ensureDanceSchedule(); // settle viewer TTL cleanup before reporting counts, and fill each room's schedule
      const now = Date.now();
      const rooms = [...getDanceRoomCharacterIds()]
        .filter((id) => !isBlacklisted("character", id))
        .map((id) => characters.get(id))
        .filter((c) => c && c.status !== "expired")
        .map((c) => {
          const room = getDanceRoom(c.id);
          let idx = room.schedule.findIndex((s) => s.startAt <= now && now < s.endAt);
          if (idx === -1) idx = room.schedule.length - 1;
          const current = room.schedule[idx];
          return {
            id: c.id,
            name: c.name,
            imageUrl: c.imageUrl,
            appearanceDescriptor: c.appearanceDescriptor,
            watching: getRoomViewers(c.id).size,
            // the room list card previews this room's actual dance video,
            // not just the character's static reference photo
            previewVideoId: current ? current.videoId : null,
          };
        });
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(rooms));
      return;
    }

    // Per-room wardrobe/待选衣服列表: only garments THIS character already
    // has a generated video for (findExistingGeneratedVideo's (characterId,
    // garmentId) index — the same M.7 dedupe granularity), shuffled — this
    // is a "pick what she's already worn" list, not a request-anything
    // catalog, and viewers shouldn't see the same fixed order every visit.
    if (pathname === "/api/dance/wardrobe" && req.method === "GET") {
      const characterId = new URL(req.url, "http://x").searchParams.get("characterId");
      if (!characterId || !characters.get(characterId)) {
        res.writeHead(400, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "characterId query param must reference an existing character" }));
        return;
      }
      const garmentIdsWithVideo = new Set(
        getLibrary()
          .filter((c) => c.channel === "dance" && c.characterId === characterId && c.qcStatus !== "incorrect")
          .map((c) => c.garmentId)
      );
      const list = garments.list().filter((g) => g.isActive && garmentIdsWithVideo.has(g.id) && !isBlacklisted("garment", g.id));
      for (let i = list.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [list[i], list[j]] = [list[j], list[i]];
      }
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(list));
      return;
    }

    // T28/T29 need pricing (spend_garment's cost, topup_tier options) on
    // the client before any purchase decision — public/unauthenticated on
    // purpose, same reasoning as GET /api/dance/wardrobe above.
    if (pathname === "/api/pricing" && req.method === "GET") {
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(pricing.list().filter((p) => p.isActive)));
      return;
    }

    if (pathname === "/api/dance/live/state" && req.method === "GET") {
      const params = new URL(req.url, "http://x").searchParams;
      const characterId = params.get("characterId");
      if (!characterId || !characters.get(characterId)) {
        res.writeHead(400, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "characterId query param must reference an existing character" }));
        return;
      }
      ensureDanceSchedule();
      const now = Date.now();
      const cid = params.get("cid");
      const uid = params.get("uid") || null;
      if (cid) getRoomViewers(characterId).set(cid, now);
      const room = getDanceRoom(characterId);
      let idx = room.schedule.findIndex((s) => s.startAt <= now && now < s.endAt);
      if (idx === -1) idx = room.schedule.length - 1;
      const cur = room.schedule[idx];
      const lib = getLibrary();
      const joinClip = (videoId) => lib.find((c) => c.id === videoId) || null;
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(
        JSON.stringify({
          now,
          watching: getRoomViewers(characterId).size,
          current: cur ? { clip: joinClip(cur.videoId), startAt: cur.startAt, endAt: cur.endAt, requestedBy: cur.requestedBy || null } : null,
          upNext: room.schedule.slice(idx + 1, idx + 4).map((s) => ({ ...(joinClip(s.videoId) || {}), requestedBy: s.requestedBy || null })),
          queue: room.queue
            .filter((q) => ["generating", "failed"].includes(q.status))
            .slice()
            .sort((a, b) => voteCount(b) - voteCount(a))
            .map((q) => ({
              id: q.id,
              garmentId: q.garmentId,
              nickname: q.nickname,
              status: q.status,
              error: q.error,
              votes: voteCount(q),
              voted: uid ? (q.votes || []).includes(uid) : false,
            })),
        })
      );
      return;
    }

    // 模式一:{characterId, garmentId, nickname?} — which room, and which of
    // that room's already-rendered garments (GET /api/dance/wardrobe above
    // already restricts the choices to that pair, so this is always a cache
    // hit through submitGeneration's M.7 dedupe, never a fresh generation).
    // 3.1 节: 免费用户不能指定/上传人物 still holds — you can only dress the
    // room's own character, not switch her out.
    if (pathname === "/api/dance/pick" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          const character = characters.get(body.characterId);
          if (!character) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "characterId must reference an existing character" }));
            return;
          }
          const garment = garments.get(body.garmentId);
          if (!garment || !garment.isActive) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "garmentId must reference an active garment" }));
            return;
          }
          // T39 (M.11): a blacklisted garment is rejected at the submission
          // entry point itself — "不进流水线、不扣积分" (moot here, mode 1
          // is free, but the entry-point rejection still applies).
          if (isBlacklisted("garment", garment.id)) {
            res.writeHead(403, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "this garment is unavailable" }));
            return;
          }
          const { status, body: respBody } = submitGeneration({ characterId: character.id, garmentId: garment.id });
          if (status !== 200) {
            res.writeHead(status, { "Content-Type": "application/json" });
            res.end(JSON.stringify(respBody));
            return;
          }
          const entry = {
            id: crypto.randomUUID(),
            garmentId: garment.id,
            characterId: character.id,
            nickname: (body.nickname || "").trim() || null,
            submittedAt: Date.now(),
            votes: [],
          };
          if (respBody.cached) {
            entry.status = "ready";
            entry.videoId = respBody.clip.id;
          } else {
            entry.status = "generating";
            entry.jobId = respBody.jobId;
          }
          getDanceRoom(character.id).queue.push(entry);
          saveDanceState();
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ status: entry.status, id: entry.id, videoId: entry.videoId || null }));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    // T38 (dev-plan-5.md): "我的作品" — 需求文档 7.4 节: expired/下线的
    // user_paid characters (T36) and their videos must stay individually
    // retrievable by their owner, "下线=不再出现在公开直播间和其他人的
    // 衣柜/随机池里",不是"下线=消失". Login required, no emailVerified
    // gate — this is a read of your own past purchases, not a new spend.
    if (pathname === "/api/dance/my-works" && req.method === "GET") {
      const user = requireUserSession(req);
      if (!user) {
        res.writeHead(401, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "login required" }));
        return;
      }
      const lib = getLibrary();
      const myCharacters = characters.list().filter((c) => c.ownerUserId === user.id);
      const myGarments = garments.list().filter((g) => g.ownerUserId === user.id);
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(
        JSON.stringify({
          characters: myCharacters.map((c) => ({ ...c, videos: lib.filter((clip) => clip.characterId === c.id) })),
          garments: myGarments.map((g) => ({ ...g, videos: lib.filter((clip) => clip.garmentId === g.id) })),
        })
      );
      return;
    }

    // T27 模式二: 付费传衣服. 需登录 + emailVerified (M.10). Order matters —
    // moderation runs before any garments record or spend exists (a
    // rejected upload leaves nothing behind); the garment record is
    // created before spend so the ledger row can carry relatedAssetId, and
    // is rolled back (garments.remove) if the spend or the generation
    // submission itself fails, so a failed/rejected attempt never leaves a
    // phantom garment in the library. Async generation failures (after
    // this handler has already responded) are refunded from
    // ensureDanceSchedule's tick instead — see its own comment.
    if (pathname === "/api/dance/upload-garment" && req.method === "POST") {
      const user = requireUserSession(req);
      if (!user) {
        res.writeHead(401, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "login required" }));
        return;
      }
      if (!user.emailVerified) {
        res.writeHead(403, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "email verification required before uploading a garment" }));
        return;
      }
      // T39 (M.11): a blacklisted account is rejected at the submission
      // entry point — "不进流水线、不扣积分".
      if (isBlacklisted("user", user.id)) {
        res.writeHead(403, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "account unavailable" }));
        return;
      }
      const boundary = boundaryFromContentType(req.headers["content-type"] || "");
      if (!boundary) {
        res.writeHead(400, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "expected multipart/form-data" }));
        return;
      }
      readRawBody(req)
        .then(async (raw) => {
          const parts = parseMultipart(raw, boundary);
          const filePart = parts.find((p) => p.name === "file");
          if (!filePart) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "missing file field" }));
            return;
          }
          const sniffed = sniffImageType(filePart.data);
          if (!sniffed) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "unrecognized image type (expected jpeg/png/webp)" }));
            return;
          }
          // Which room you're uploading from — the garment still joins the
          // global wardrobe pool once generated (every room can pick it
          // later), but the upload itself dresses THIS room's character
          // first (confirmed: "上传衣服=全局衣柜,所有房间都能选").
          const characterIdPart = parts.find((p) => p.name === "characterId");
          const targetCharacter = characterIdPart ? characters.get(characterIdPart.data.toString("utf8").trim()) : null;
          if (!targetCharacter) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "characterId must reference an existing character (which room you're in)" }));
            return;
          }

          let relPath, absPath;
          try {
            ({ relPath } = stripMetadataAndSave(filePart.data, sniffed));
            absPath = path.join(__dirname, relPath);
          } catch {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "failed to process image" }));
            return;
          }

          const moderation = await moderateGarmentImage(absPath, relPath);
          if (!moderation.approved) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "image rejected by moderation", reason: moderation.reason }));
            return;
          }

          const appearanceDescriptor = await describeGarmentImage(absPath);
          const garment = garments.create({
            name: `${user.nickname || user.email.split("@")[0]} 上传`,
            category: "",
            thumbnailUrl: relPath,
            imageUrl: relPath,
            appearanceDescriptor,
            source: "user_paid",
            ownerUserId: user.id,
            moderationStatus: "approved",
            isActive: true,
          });

          const spendGarment = pricing.get("spend_garment");
          const amount = spendGarment ? spendGarment.credits : 0;
          let spendRow;
          try {
            spendRow = creditLedger.spend({ userId: user.id, amount, reason: "spend_garment", relatedAssetId: garment.id });
          } catch (err) {
            garments.remove(garment.id);
            const status = err.code === "INSUFFICIENT_BALANCE" ? 402 : 500;
            res.writeHead(status, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: err.message }));
            return;
          }

          // userId (T33): mode 2 is a paid request, so this both fixes M.7's
          // requestedByUserId tracking (previously always null — a gap left
          // over from T27) and makes it fal-eligible once FAL_API_KEY is
          // configured. priority stays "normal" (T27/dev-plan-4.md's
          // explicit scope: only mode 3 skips voting, mode 2 doesn't).
          const { status, body: respBody } = submitGeneration({ characterId: targetCharacter.id, garmentId: garment.id, userId: user.id });
          if (status !== 200) {
            creditLedger.refund({ userId: user.id, amount, reason: "refund_stage2_fail", relatedAssetId: garment.id });
            garments.remove(garment.id);
            res.writeHead(status, { "Content-Type": "application/json" });
            res.end(JSON.stringify(respBody));
            return;
          }

          const entry = {
            id: crypto.randomUUID(),
            garmentId: garment.id,
            characterId: targetCharacter.id,
            nickname: user.nickname || null,
            userId: user.id,
            amountPaid: amount,
            submittedAt: Date.now(),
            votes: [],
          };
          if (respBody.cached) {
            entry.status = "ready";
            entry.videoId = respBody.clip.id;
          } else {
            entry.status = "generating";
            entry.jobId = respBody.jobId;
          }
          getDanceRoom(targetCharacter.id).queue.push(entry);
          saveDanceState();
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ status: entry.status, id: entry.id, garmentId: garment.id, videoId: entry.videoId || null, creditsSpent: amount, balanceAfter: spendRow.balanceAfter }));
        })
        .catch((err) => {
          if (res.writableEnded) return;
          const status = err.code === "PAYLOAD_TOO_LARGE" ? 413 : 400;
          res.writeHead(status, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: err.message || "upload failed" }));
        });
      return;
    }

    // T35 模式三: 付费传人物 (dev-plan-5.md). 需登录 + emailVerified, same
    // rule as T27. Differs from T27 in three structural ways: (1) the
    // upload itself becomes the new characters record (not paired with an
    // existing default character — garment is what's optional/random here,
    //需求文档 3.3 第 4 点); (2) cost scales with how many 10s segments the
    // buyer requests (M.12's segmentsPerUnit), not a flat per-upload price;
    // (3) the produced clip carries priority:"paid_boost" end to end
    // (submitGeneration -> generationJobs -> either straight into
    // priorityInbox if cached, or into danceQueue to be diverted there once
    // T34's ensureDanceSchedule reconciliation sees the job land) — it
    // never enters the vote-ranked path T27's mode-2 entries do.
    if (pathname === "/api/dance/upload-character" && req.method === "POST") {
      const user = requireUserSession(req);
      if (!user) {
        res.writeHead(401, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "login required" }));
        return;
      }
      if (!user.emailVerified) {
        res.writeHead(403, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "email verification required before uploading a character" }));
        return;
      }
      if (isBlacklisted("user", user.id)) {
        res.writeHead(403, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "account unavailable" }));
        return;
      }
      const boundary = boundaryFromContentType(req.headers["content-type"] || "");
      if (!boundary) {
        res.writeHead(400, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "expected multipart/form-data" }));
        return;
      }
      readRawBody(req)
        .then(async (raw) => {
          const parts = parseMultipart(raw, boundary);
          const filePart = parts.find((p) => p.name === "file");
          if (!filePart) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "missing file field" }));
            return;
          }
          const sniffed = sniffImageType(filePart.data);
          if (!sniffed) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "unrecognized image type (expected jpeg/png/webp)" }));
            return;
          }

          // 需求文档 3.3 第 4 点:衣服可选,指定就用指定的,否则系统随机
          // 挑一件衣柜库服装.
          const garmentIdPart = parts.find((p) => p.name === "garmentId");
          const requestedGarmentId = garmentIdPart ? garmentIdPart.data.toString("utf8").trim() : "";
          let targetGarment;
          if (requestedGarmentId) {
            targetGarment = garments.get(requestedGarmentId);
            if (!targetGarment || !targetGarment.isActive) {
              res.writeHead(400, { "Content-Type": "application/json" });
              res.end(JSON.stringify({ error: "garmentId must reference an active garment" }));
              return;
            }
          } else {
            const activeGarments = garments.list().filter((g) => g.isActive);
            if (!activeGarments.length) {
              res.writeHead(400, { "Content-Type": "application/json" });
              res.end(JSON.stringify({ error: "no active garments available to pair with the new character" }));
              return;
            }
            targetGarment = activeGarments[Math.floor(Math.random() * activeGarments.length)];
          }

          // 需求文档 3.3 第 3 点:花的积分决定能播放几个 10 秒片段.
          const segmentsPart = parts.find((p) => p.name === "segments");
          const requestedSegments = Math.min(20, Math.max(1, parseInt(segmentsPart ? segmentsPart.data.toString("utf8").trim() : "3", 10) || 3));
          const pricingEntry = pricing.get("spend_character_per_segment");
          if (!pricingEntry) {
            res.writeHead(500, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "spend_character_per_segment pricing not configured" }));
            return;
          }
          const cost = Math.ceil((pricingEntry.credits / (pricingEntry.segmentsPerUnit || 1)) * requestedSegments);

          let relPath, absPath;
          try {
            ({ relPath } = stripMetadataAndSave(filePart.data, sniffed));
            absPath = path.join(__dirname, relPath);
          } catch {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "failed to process image" }));
            return;
          }

          const moderation = await moderateFaceBlacklist(absPath, relPath);
          if (!moderation.approved) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "image rejected by moderation", reason: moderation.reason }));
            return;
          }

          const appearanceDescriptor = await describeCharacterImage(absPath);
          // 需求文档 3.3 第 6 点:新人物默认不沉淀进公共人物池(isDefault
          // 恒为 false,且不会被 /api/dance/pick 的默认人物逻辑抽中——那条
          // 逻辑只认 isDefault:true,一个 user_paid 人物永远不会是它)。
          const character = characters.create({
            name: `${user.nickname || user.email.split("@")[0]} 的新角色`,
            imageUrl: relPath,
            tags: [],
            source: "user_paid",
            ownerUserId: user.id,
            appearanceDescriptor,
            isDefault: false,
            moderationStatus: "auto_passed",
            totalSegments: requestedSegments,
            remainingSegments: requestedSegments,
            status: "active",
          });

          let spendRow;
          try {
            spendRow = creditLedger.spend({ userId: user.id, amount: cost, reason: "spend_character", relatedAssetId: character.id });
          } catch (err) {
            characters.remove(character.id);
            const status = err.code === "INSUFFICIENT_BALANCE" ? 402 : 500;
            res.writeHead(status, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: err.message }));
            return;
          }

          // priority:"paid_boost" (T34) — this is the one call site in the
          // whole codebase that requests it; mode 2 (T27) never does.
          const { status, body: respBody } = submitGeneration({
            characterId: character.id,
            garmentId: targetGarment.id,
            userId: user.id,
            priority: "paid_boost",
          });
          if (status !== 200) {
            creditLedger.refund({ userId: user.id, amount: cost, reason: "refund_stage2_fail", relatedAssetId: character.id });
            characters.remove(character.id);
            res.writeHead(status, { "Content-Type": "application/json" });
            res.end(JSON.stringify(respBody));
            return;
          }

          const entry = {
            id: crypto.randomUUID(),
            characterId: character.id,
            garmentId: targetGarment.id,
            nickname: user.nickname || null,
            userId: user.id,
            amountPaid: cost,
            priority: "paid_boost",
            submittedAt: Date.now(),
            votes: [],
          };
          // This character has never had a room before this call — its
          // first video (whether cached-instant or generated below) is what
          // creates one (getDanceRoomCharacterIds: "有视频就自动开间").
          const room = getDanceRoom(character.id);
          let videoId = null;
          if (respBody.cached) {
            // M.7 去重缓存命中是即时的 —— T34 的 ensureDanceSchedule 转运
            // 逻辑只在意"generating -> done"这个过渡,命中缓存跳过了整个
            // 过渡,所以这里直接进 priorityInbox,不经过 room.queue。
            videoId = respBody.clip.id;
            room.priorityInbox.push({ videoId, requestedBy: entry.nickname });
          } else {
            entry.status = "generating";
            entry.jobId = respBody.jobId;
            room.queue.push(entry);
          }
          saveDanceState();
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(
            JSON.stringify({
              status: respBody.cached ? "ready" : entry.status,
              id: entry.id,
              characterId: character.id,
              garmentId: targetGarment.id,
              videoId,
              creditsSpent: cost,
              totalSegments: requestedSegments,
              balanceAfter: spendRow.balanceAfter,
            })
          );
        })
        .catch((err) => {
          if (res.writableEnded) return;
          const status = err.code === "PAYLOAD_TOO_LARGE" ? 413 : 400;
          res.writeHead(status, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: err.message || "upload failed" }));
        });
      return;
    }

    if (pathname.startsWith("/api/dance/queue/vote/") && req.method === "POST") {
      const id = pathname.slice("/api/dance/queue/vote/".length);
      readJsonBody(req)
        .then((body) => {
          const uid = (body.uid || "").trim();
          if (!uid) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "uid required" }));
            return;
          }
          // id alone doesn't say which room's queue this is in — a vote can
          // land on any room, so search all of them.
          let entry;
          for (const room of Object.values(danceRooms)) {
            entry = room.queue.find((q) => q.id === id);
            if (entry) break;
          }
          if (!entry || !["generating", "ready", "failed"].includes(entry.status)) {
            res.writeHead(404, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "not found" }));
            return;
          }
          if (!Array.isArray(entry.votes)) entry.votes = [];
          const i = entry.votes.indexOf(uid);
          const voted = i === -1;
          if (voted) entry.votes.push(uid);
          else entry.votes.splice(i, 1);
          saveDanceState();
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ votes: entry.votes.length, voted }));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    if (pathname === "/api/library") {
      const sort = new URL(req.url, "http://x").searchParams.get("sort") || "newest";
      const lib = getLibrary().slice();
      const sorters = {
        newest: (a, b) => b.createdAt - a.createdAt,
        oldest: (a, b) => a.createdAt - b.createdAt,
        top: (a, b) => (b.likes || 0) - (a.likes || 0) || b.createdAt - a.createdAt,
      };
      lib.sort(sorters[sort] || sorters.newest);
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(lib));
      return;
    }

    if (pathname === "/api/live/state") {
      ensureSchedule();
      const now = Date.now();
      const params = new URL(req.url, "http://x").searchParams;
      const cid = params.get("cid");
      const uid = params.get("uid") || null;
      if (cid) viewers.set(cid, now);
      let idx = schedule.findIndex((s) => s.startAt <= now && now < s.endAt);
      if (idx === -1) idx = schedule.length - 1;
      const cur = schedule[idx];
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(
        JSON.stringify({
          now,
          watching: viewers.size,
          current: cur ? { clip: cur.clip, startAt: cur.startAt, endAt: cur.endAt, requestedBy: cur.requestedBy || null } : null,
          upNext: schedule.slice(idx + 1, idx + 4).map((s) => ({ ...s.clip, requestedBy: s.requestedBy || null })),
          queue: promptQueue
            .filter((q) => ["matched", "generating", "failed"].includes(q.status))
            .slice()
            .sort((a, b) => voteCount(b) - voteCount(a))
            .map((q) => ({
              id: q.id,
              prompt: q.prompt,
              nickname: q.nickname,
              status: q.status,
              error: q.error,
              votes: voteCount(q),
              voted: uid ? (q.votes || []).includes(uid) : false,
            })),
        })
      );
      return;
    }

    if (pathname === "/api/prompt" && req.method === "POST") {
      if (isRateLimited(req.socket.remoteAddress)) {
        res.writeHead(429, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: `最多每 ${RATE_LIMIT_WINDOW_MS / 60000} 分钟提交 ${RATE_LIMIT_MAX} 次,请稍后再试` }));
        return;
      }
      readJsonBody(req)
        .then((body) => {
          const prompt = (body.prompt || "").trim();
          if (!prompt || prompt.length > 300) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "prompt required, max 300 chars" }));
            return;
          }
          const result = submitPromptToQueue(Date.now().toString(36), prompt, null);
          saveLiveState();
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(result));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    if (pathname === "/api/chat" && req.method === "GET") {
      const cid = new URL(req.url, "http://x").searchParams.get("cid");
      if (cid) viewers.set(cid, Date.now());
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(chatMessages.slice(-100)));
      return;
    }

    if (pathname === "/api/chat" && req.method === "POST") {
      if (isRateLimited(req.socket.remoteAddress)) {
        res.writeHead(429, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: `最多每 ${RATE_LIMIT_WINDOW_MS / 60000} 分钟发送 ${RATE_LIMIT_MAX} 条,请稍后再试` }));
        return;
      }
      readJsonBody(req)
        .then((body) => {
          const uid = (body.uid || "").trim();
          const nickname = (body.nickname || "").trim().slice(0, 20);
          const text = (body.text || "").trim();
          if (!uid || !nickname || !text || text.length > 300) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "uid, nickname, text required, text max 300 chars" }));
            return;
          }
          const id = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
          const msg = { id, uid, nickname, text, createdAt: Date.now() };

          const mod = moderateText(text);
          if (!mod.ok) {
            msg.status = "rejected";
            msg.rejectReason = mod.reason;
            pushChatMessage(msg);
            saveLiveState();
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ status: "rejected", reason: mod.reason }));
            return;
          }

          msg.status = "approved";
          pushChatMessage(msg);
          const result = submitPromptToQueue(id, text, nickname);
          msg.status = result.status; // "matched" | "generating"
          saveLiveState();
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(result));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    if (pathname === "/api/admin/library" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          const prompt = (body.prompt || "").trim();
          const videoUrl = (body.videoUrl || "").trim();
          if (!prompt || !videoUrl) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "prompt and videoUrl required" }));
            return;
          }
          const clip = {
            id: `manual-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
            source: "manual",
            edited: true,
            prompt,
            promptEn: (body.promptEn || "").trim(),
            fullPrompt: (body.fullPrompt || prompt).trim(),
            videoUrl,
            width: body.width || null,
            height: body.height || null,
            duration: body.duration || null,
            partition: "manual",
            likes: 0,
            createdAt: Date.now(),
            // channel: "dance" puts this clip in dance.html's pool
            // (pickNextClip filters on it, architecture.md 2.1); anything
            // else stays out of it and is live.html's/text-channel pool.
            channel: body.channel === "dance" ? "dance" : undefined,
          };
          const lib = getLibrary();
          lib.push(clip);
          saveLibrary(lib);
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(clip));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    if (pathname.startsWith("/api/admin/library/") && req.method === "PATCH") {
      const id = pathname.slice("/api/admin/library/".length);
      readJsonBody(req)
        .then((body) => {
          const lib = getLibrary();
          const clip = lib.find((c) => c.id === id);
          if (!clip) {
            res.writeHead(404, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "not found" }));
            return;
          }
          for (const field of ["prompt", "promptEn", "fullPrompt", "videoUrl"]) {
            if (typeof body[field] === "string" && body[field].trim()) clip[field] = body[field].trim();
          }
          // qcStatus/qcNote (2026-09 video QC): admin manually overriding an
          // AI verdict or setting one by hand — qcNote allowed to be blanked
          // out (e.g. clearing a note when flipping back to "correct"), so
          // it's handled separately from the trim-if-nonblank fields above.
          if (body.qcStatus === "pending" || body.qcStatus === "correct" || body.qcStatus === "incorrect") {
            clip.qcStatus = body.qcStatus;
            clip.published = body.qcStatus === "correct"; // 通过验证的自动上架
          }
          if (typeof body.qcNote === "string") clip.qcNote = body.qcNote.trim();
          if (body.channel === "dance" || body.channel === "video") clip.channel = body.channel === "dance" ? "dance" : undefined;
          // 上架/下架 (2026-09): explicit manual override, applied after the
          // auto-publish-on-QC above so an admin toggle in the same request
          // (or a later one) always wins over the automatic default.
          if (body.published === true || body.published === "true") clip.published = true;
          else if (body.published === false || body.published === "false") clip.published = false;
          // Storing a videoUrl (whether this clip started as h3console or
          // manual) means /lib/video/:id should serve that directly instead
          // of proxying the H3 console — see the handler below.
          if (body.videoUrl) clip.source = "manual";
          // Marks this entry as admin-owned so the periodic H3 library sync
          // (ingest.js's syncLibrary) carries it forward as-is instead of
          // overwriting it with a freshly re-extracted prompt.
          clip.edited = true;
          saveLibrary(lib);
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(clip));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    if (pathname.startsWith("/api/admin/library/") && req.method === "DELETE") {
      const id = pathname.slice("/api/admin/library/".length);
      const lib = getLibrary();
      const clip = lib.find((c) => c.id === id);
      if (!clip) {
        res.writeHead(404, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "not found" }));
        return;
      }
      saveLibrary(lib.filter((c) => c.id !== id));
      // Without this, the next periodic syncLibrary() would just re-add it —
      // it's still a "done" job on the H3 console until explicitly deleted there too.
      const cleanup = clip.source === "h3console" ? h3ConsoleFetch(`/v1/videos/${id}`, { method: "DELETE" }).catch(() => {}) : Promise.resolve();
      cleanup.then(() => {
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ deleted: true }));
      });
      return;
    }

    // Single-clip AI QC check (admin-dance-library.html's per-row "AI检查"
    // button) — synchronous, returns the updated clip once GLM responds.
    if (pathname.startsWith("/api/admin/library/") && pathname.endsWith("/qc-check") && req.method === "POST") {
      const id = pathname.slice("/api/admin/library/".length, -"/qc-check".length);
      const lib = getLibrary();
      const clip = lib.find((c) => c.id === id && c.channel === "dance");
      if (!clip) {
        res.writeHead(404, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "not found" }));
        return;
      }
      runDanceClipQc(clip)
        .then(({ qcStatus, qcNote }) => {
          clip.qcStatus = qcStatus;
          clip.qcNote = qcNote;
          clip.published = qcStatus === "correct"; // 通过验证的自动上架
          saveLibrary(lib);
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(clip));
        })
        .catch((err) => {
          res.writeHead(502, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: err.message }));
        });
      return;
    }

    // Batch AI QC (admin-dance-qc.html): {clipIds?[]} — omit clipIds to
    // check every channel:"dance" clip whose qcStatus is still "pending".
    // Fire-and-forget: returns a batchId immediately, runQcBatch works
    // through it sequentially in the background (see its own comment on
    // why sequential, not concurrent).
    if (pathname === "/api/admin/dance-qc/batch" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          const dance = getLibrary().filter((c) => c.channel === "dance");
          const clipIds = Array.isArray(body.clipIds) && body.clipIds.length ? body.clipIds : dance.filter((c) => (c.qcStatus || "pending") === "pending").map((c) => c.id);
          const batchId = crypto.randomUUID();
          qcBatchJobs.set(batchId, { total: clipIds.length, checked: 0, results: [], status: "running", cancelled: false });
          runQcBatch(batchId, clipIds).catch(() => {});
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ batchId, total: clipIds.length }));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    if (pathname.startsWith("/api/admin/dance-qc/batch/") && req.method === "GET") {
      const batchId = pathname.slice("/api/admin/dance-qc/batch/".length);
      const job = qcBatchJobs.get(batchId);
      if (!job) {
        res.writeHead(404, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "not found" }));
        return;
      }
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(job));
      return;
    }

    if (pathname.startsWith("/api/admin/dance-qc/batch/") && pathname.endsWith("/cancel") && req.method === "POST") {
      const batchId = pathname.slice("/api/admin/dance-qc/batch/".length, -"/cancel".length);
      const job = qcBatchJobs.get(batchId);
      if (job) job.cancelled = true;
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ ok: true }));
      return;
    }

    if (pathname.startsWith("/api/queue/vote/") && req.method === "POST") {
      const id = pathname.slice("/api/queue/vote/".length);
      readJsonBody(req)
        .then((body) => {
          const uid = (body.uid || "").trim();
          if (!uid) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "uid required" }));
            return;
          }
          const entry = promptQueue.find((q) => q.id === id);
          if (!entry || !["matched", "generating", "ready"].includes(entry.status)) {
            res.writeHead(404, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "not found" }));
            return;
          }
          if (!Array.isArray(entry.votes)) entry.votes = [];
          const i = entry.votes.indexOf(uid);
          const voted = i === -1;
          if (voted) entry.votes.push(uid);
          else entry.votes.splice(i, 1);
          saveLiveState();
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ votes: entry.votes.length, voted }));
        })
        .catch(() => {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "invalid JSON body" }));
        });
      return;
    }

    if (pathname.startsWith("/api/like/") && req.method === "POST") {
      const id = pathname.slice("/api/like/".length);
      const lib = getLibrary();
      const clip = lib.find((c) => c.id === id);
      if (!clip) {
        res.writeHead(404, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "not found" }));
        return;
      }
      clip.likes = (clip.likes || 0) + 1;
      saveLibrary(lib);
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ likes: clip.likes }));
      return;
    }

    if (pathname === "/api/admin/upload" && req.method === "POST") {
      const boundary = boundaryFromContentType(req.headers["content-type"] || "");
      if (!boundary) {
        res.writeHead(400, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "expected multipart/form-data" }));
        return;
      }
      readRawBody(req)
        .then((body) => {
          const filePart = parseMultipart(body, boundary).find((p) => p.name === "file");
          if (!filePart) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "missing file field" }));
            return;
          }
          const sniffed = sniffImageType(filePart.data);
          if (!sniffed) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "unrecognized image type (expected jpeg/png/webp)" }));
            return;
          }
          try {
            const { relPath } = stripMetadataAndSave(filePart.data, sniffed);
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ url: relPath }));
          } catch {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "failed to process image" }));
          }
        })
        .catch((err) => {
          if (res.writableEnded) return;
          try {
            const status = err.code === "PAYLOAD_TOO_LARGE" ? 413 : 400;
            res.writeHead(status, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: err.message }));
          } catch {
            // socket already gone (e.g. destroyed for exceeding the size cap)
          }
        });
      return;
    }

    if (pathname === "/api/admin/upload-video" && req.method === "POST") {
      const boundary = boundaryFromContentType(req.headers["content-type"] || "");
      if (!boundary) {
        res.writeHead(400, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "expected multipart/form-data" }));
        return;
      }
      readRawBody(req, 50 * 1024 * 1024)
        .then((body) => {
          const filePart = parseMultipart(body, boundary).find((p) => p.name === "file");
          if (!filePart) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "missing file field" }));
            return;
          }
          const sniffed = sniffVideoType(filePart.data);
          if (!sniffed) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "unrecognized video type (expected mp4)" }));
            return;
          }
          const { relPath } = saveVideoUpload(filePart.data, sniffed);
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ url: relPath }));
        })
        .catch((err) => {
          if (res.writableEnded) return;
          try {
            const status = err.code === "PAYLOAD_TOO_LARGE" ? 413 : 400;
            res.writeHead(status, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: err.message }));
          } catch {
            // socket already gone (e.g. destroyed for exceeding the size cap)
          }
        });
      return;
    }

    if (pathname.startsWith("/uploads/")) {
      const rel = pathname.slice("/uploads/".length);
      const abs = path.join(UPLOADS_DIR, rel);
      if (!abs.startsWith(UPLOADS_DIR + path.sep)) {
        res.writeHead(403);
        res.end("Forbidden");
        return;
      }
      // Range support is required here, not optional: <video> elements probe
      // duration/seekability with a Range request, and without a 206 reply
      // (plus Content-Length) Chrome's media pipeline can get stuck at
      // readyState 0 forever — the video never becomes playable.
      fs.stat(abs, (err, stat) => {
        if (err || !stat.isFile()) {
          res.writeHead(404);
          res.end("Not found");
          return;
        }
        const contentType = MIME[path.extname(abs)] || "application/octet-stream";
        const range = req.headers.range;
        const match = range && /^bytes=(\d*)-(\d*)$/.exec(range);
        if (match) {
          const start = match[1] ? parseInt(match[1], 10) : 0;
          const end = match[2] ? parseInt(match[2], 10) : stat.size - 1;
          if (start > end || end >= stat.size) {
            res.writeHead(416, { "Content-Range": `bytes */${stat.size}` });
            res.end();
            return;
          }
          res.writeHead(206, {
            "Content-Type": contentType,
            "Content-Length": end - start + 1,
            "Content-Range": `bytes ${start}-${end}/${stat.size}`,
            "Accept-Ranges": "bytes",
          });
          fs.createReadStream(abs, { start, end }).pipe(res);
          return;
        }
        res.writeHead(200, { "Content-Type": contentType, "Content-Length": stat.size, "Accept-Ranges": "bytes" });
        fs.createReadStream(abs).pipe(res);
      });
      return;
    }

    if (pathname.startsWith("/lib/video/")) {
      const id = pathname.slice("/lib/video/".length);
      const clip = getLibrary().find((c) => c.id === id);
      if (clip && clip.videoUrl) {
        res.writeHead(302, { Location: clip.videoUrl });
        res.end();
        return;
      }
      if (!H3_CONSOLE_URL) {
        res.writeHead(500, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "H3_CONSOLE_BASE not configured" }));
        return;
      }
      const upstreamHeaders = { Authorization: `Bearer ${H3_CONSOLE_TOKEN}` };
      if (req.headers.range) upstreamHeaders.range = req.headers.range;
      const proxyReq = http.request(
        {
          hostname: H3_CONSOLE_URL.hostname,
          port: H3_CONSOLE_URL.port || 80,
          path: `${H3_CONSOLE_URL.pathname}/v1/videos/${id}/file`,
          method: "GET",
          headers: upstreamHeaders,
        },
        (proxyRes) => {
          res.writeHead(proxyRes.statusCode, proxyRes.headers);
          proxyRes.pipe(res);
        }
      );
      proxyReq.on("error", (err) => {
        res.writeHead(502, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: { message: err.message } }));
      });
      proxyReq.end();
      return;
    }
    const filePath = path.join(__dirname, pathname === "/" ? "/index.html" : pathname);
    fs.readFile(filePath, (err, data) => {
      if (err) {
        res.writeHead(404);
        res.end("Not found");
        return;
      }
      res.writeHead(200, { "Content-Type": MIME[path.extname(filePath)] || "application/octet-stream" });
      res.end(data);
    });
  })
  .listen(PORT, () => console.log(`http://localhost:${PORT}`));

resumeGenerations();
resumeDressupGenerations();
resumeDressgenTasks();

// Auto-sync the library from the H3 Console so content added there directly
// (not through our own /api/prompt) shows up without a manual `node ingest.js`.
const LIBRARY_SYNC_INTERVAL_MS = 5 * 60 * 1000;
syncLibrary()
  .then((n) => console.log(`library synced — ${n} clips`))
  .catch((err) => console.error(`library sync failed: ${err.message}`));
setInterval(() => {
  syncLibrary().catch((err) => console.error(`library sync failed: ${err.message}`));
}, LIBRARY_SYNC_INTERVAL_MS);