server.js 64.6 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
// 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 crypto = require("crypto");

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";

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,
  forwardToH3Assets,
} = require("./uploads.js");
const { characters, garments, danceRefs, generationJobs } = require("./dressup-store.js");
const { buildStage2Prompt } = require("./prompt-template.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));
}

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.
const DANCE_STATE_PATH = path.join(__dirname, "dance-state.json");
function loadDanceState() {
  try {
    const s = JSON.parse(fs.readFileSync(DANCE_STATE_PATH, "utf8"));
    return { danceSchedule: s.schedule || [], danceQueue: s.freeQueue || [] };
  } catch {
    return { danceSchedule: [], danceQueue: [] };
  }
}
function saveDanceState() {
  fs.writeFileSync(DANCE_STATE_PATH, JSON.stringify({ schedule: danceSchedule, freeQueue: danceQueue }, null, 2));
}

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);
  });
}

// 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;
}

function isAdminAuthed(req) {
  const token = parseCookies(req)[ADMIN_SESSION_COOKIE];
  if (!token) return false;
  const expiresAt = adminSessions.get(token);
  if (!expiresAt || expiresAt < Date.now()) {
    adminSessions.delete(token);
    return false;
  }
  return true;
}

// 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 } = 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 removed = store.remove(id);
      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: unsetOtherDefaultCharacters,
  onUpdate: unsetOtherDefaultCharacters,
});

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),
        },
});

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();
  });
}

function glmChat(messages) {
  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(15000, () => req.destroy(new Error("GLM request timed out")));
    req.write(body);
    req.end();
  });
}

// 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;
  }
}

// ---- 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();
let danceSchedule = initialDanceState.danceSchedule; // [{videoId, startAt, endAt, requestedBy?}]
let danceQueue = initialDanceState.danceQueue; // [{id, garmentId, characterId, nickname?, status, jobId?, videoId?, error?, submittedAt, votes}]

// 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);
}

// 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) — the two channels' "在线人数"
// must not be summed together, they're separate rooms.
const danceViewers = new 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;
}

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) 组合直接复用已有产物。
function findExistingGeneratedVideo(characterId, garmentId) {
  return getLibrary().find((c) => c.channel === "dance" && c.characterId === characterId && c.garmentId === garmentId);
}

// 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.
function submitGeneration({ characterId, garmentId, refDanceVideoId, batchId }) {
  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 } };
    }
  }
  const job = generationJobs.create({ characterId, garmentId, refDanceVideoId, batchId: batchId || null, status: "queued", h3JobId: null, error: null });
  generateDanceVideo(job).catch(() => {});
  return { status: 200, body: { cached: false, jobId: job.id } };
}

// job: a generationJobs record ({id, characterId, garmentId,
// refDanceVideoId, status, h3JobId, error, fullPrompt}). 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 generateDanceVideo(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" });
    }

    for (let i = 0; i < 200; i++) {
      await new Promise((r) => setTimeout(r, pollIntervalMs));
      const polled = await h3ConsoleFetch(`/v1/videos/${job.h3JobId}`);
      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: "normal",
          requestedByUserId: 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") throw new Error(polled.error || "generation failed");
    }
    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;
    if (job.h3JobId) generateDanceVideo(job).catch(() => {});
    else generationJobs.update(job.id, { status: "failed", error: "lost track of this generation across a restart" });
  }
}

// ---- dance.html: independent playout schedule + free (mode-一/衣柜) queue (T11) ----
// Mirrors live's pickNextClip/ensureSchedule shape but pulls from
// danceQueue/danceSchedule instead, and picks its random-fill pool from
// channel:"dance" clips only.

function pickNextDanceClip() {
  const readyIdx = pickBestIndexByStatus(danceQueue, "ready");
  if (readyIdx !== -1) {
    const q = danceQueue.splice(readyIdx, 1)[0];
    return { videoId: q.videoId, requestedBy: q.nickname };
  }
  const pool = getLibrary().filter((c) => c.channel === "dance");
  if (!pool.length) return null;
  const prevVideoId = danceSchedule.length ? danceSchedule[danceSchedule.length - 1].videoId : null;
  const clip = pickLeastPlayedClip(pool, prevVideoId);
  return clip ? { videoId: clip.id, requestedBy: null } : null;
}

function ensureDanceSchedule() {
  const now = Date.now();

  // 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).
  for (const q of danceQueue) {
    if (q.status !== "generating" || !q.jobId) continue;
    const job = generationJobs.get(q.jobId);
    if (!job) continue;
    if (job.status === "done") {
      q.status = "ready";
      q.videoId = job.generatedVideoId;
    } else if (job.status === "failed") {
      q.status = "failed";
      q.error = job.error;
      q.failedAt = now;
    }
  }

  while (danceSchedule.length > 1 && danceSchedule[1].endAt <= now) danceSchedule.shift();
  while (danceSchedule.length === 0 || danceSchedule[danceSchedule.length - 1].endAt < now + FILLER_DURATION_MS) {
    const picked = pickNextDanceClip();
    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);
    const startAt = danceSchedule.length ? danceSchedule[danceSchedule.length - 1].endAt : now;
    danceSchedule.push({ videoId: picked.videoId, startAt, endAt: startAt + clip.duration * 1000, requestedBy: picked.requestedBy });
  }
  danceQueue = danceQueue.filter((q) => q.status !== "failed" || now - q.failedAt < FAILED_ENTRY_TTL_MS);

  for (const [cid, lastSeen] of danceViewers) if (now - lastSeen > VIEWER_TTL_MS) danceViewers.delete(cid);
  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;
    }

    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 (garmentsCrud(pathname, req, res)) return;
    if (danceRefsCrud(pathname, req, res)) 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. Modes 二/三 (paid upload) aren't
    // built yet (require accounts/credits, dev-plan-2.md 第三/四期).

    if (pathname === "/api/dance/wardrobe" && req.method === "GET") {
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify(garments.list().filter((g) => g.isActive)));
      return;
    }

    if (pathname === "/api/dance/live/state" && req.method === "GET") {
      ensureDanceSchedule();
      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) danceViewers.set(cid, now);
      let idx = danceSchedule.findIndex((s) => s.startAt <= now && now < s.endAt);
      if (idx === -1) idx = danceSchedule.length - 1;
      const cur = danceSchedule[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: danceViewers.size,
          current: cur ? { clip: joinClip(cur.videoId), startAt: cur.startAt, endAt: cur.endAt, requestedBy: cur.requestedBy || null } : null,
          upNext: danceSchedule.slice(idx + 1, idx + 4).map((s) => ({ ...(joinClip(s.videoId) || {}), requestedBy: s.requestedBy || null })),
          queue: danceQueue
            .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;
    }

    // P.1 免费模式一:{garmentId, nickname?}. Uses the single配置的直播默认
    // 人物 (characters.isDefault) — 3.1 节: 免费用户不能指定/上传人物。
    // Reuses submitGeneration (T8/T9) whole — same M.7 dedupe cache — then
    // hands the result to danceQueue for ensureDanceSchedule to pick up.
    if (pathname === "/api/dance/pick" && req.method === "POST") {
      readJsonBody(req)
        .then((body) => {
          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;
          }
          const defaultCharacter = characters.list().find((c) => c.isDefault);
          if (!defaultCharacter) {
            res.writeHead(400, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "no default character configured" }));
            return;
          }
          const { status, body: respBody } = submitGeneration({ characterId: defaultCharacter.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: defaultCharacter.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;
          }
          danceQueue.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;
    }

    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;
          }
          const entry = danceQueue.find((q) => q.id === id);
          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(),
          };
          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();
          }
          // 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;
    }

    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;
      }
      fs.readFile(abs, (err, data) => {
        if (err) {
          res.writeHead(404);
          res.end("Not found");
          return;
        }
        res.writeHead(200, { "Content-Type": MIME[path.extname(abs)] || "application/octet-stream" });
        res.end(data);
      });
      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();

// 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);