ai-direct-messages.mjs 70.8 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
#!/usr/bin/env node

import child_process from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";

import { requireWorkspaceRoot } from "./workspace-root.mjs";

const repoRoot = requireWorkspaceRoot();

const _tp = () => `[${new Date().toISOString().slice(11, 23)}]`;
const _log = (...args) => {
	const msg = `${_tp()} ${args.map(String).join(" ")}`;
	if (process.stdout.isTTY) {
		process.stdout.write(`${msg}\n`);
	} else {
		try { fs.writeSync(1, `${msg}\n`); } catch { /* noop */ }
	}
};

function parseCliArgs() {
	const args = process.argv.slice(2);
	const parsed = {
		bundleFile: "",
		projectDir: "",
		figmaUrl: "",
		pageName: "",
		pageTitle: "",
		outputDir: "",
		withoutVariables: false,
		appendMode: false,
		skipScreenshotSummary: false,
		singlePageMode: false,
	};

	for (let index = 0; index < args.length; index++) {
		const arg = args[index];
		const next = args[index + 1];

		if (arg === "--bundle-file" && next) {
			parsed.bundleFile = next;
			index++;
		} else if (arg === "--project-dir" && next) {
			parsed.projectDir = next;
			index++;
		} else if (arg === "--figma-url" && next) {
			parsed.figmaUrl = next;
			index++;
		} else if (arg === "--page-name" && next) {
			parsed.pageName = next;
			index++;
		} else if (arg === "--page-title" && next) {
			parsed.pageTitle = next;
			index++;
		} else if (arg === "--output-dir" && next) {
			parsed.outputDir = next;
			index++;
		} else switch (arg) {
			case "--append-mode": {
				parsed.appendMode = true;

				break;
			}
			case "--single-page-mode": {
				parsed.singlePageMode = true;

				break;
			}
			case "--skip-screenshot-summary": {
				parsed.skipScreenshotSummary = true;

				break;
			}
			case "--without-variables": {
				parsed.withoutVariables = true;

				break;
			}
 // No default
		}
	}

	return parsed;
}

function fileExists(targetPath) {
	return fs.existsSync(targetPath);
}

function readJson(filePath) {
	return JSON.parse(fs.readFileSync(filePath, "utf8"));
}

function normalizePath(targetPath) {
	return targetPath.replaceAll("\\", "/");
}

function slugify(value) {
	const normalized = String(value || "")
		.trim()
		.toLowerCase()
		.replaceAll(/[^a-z0-9]+/g, "-")
		.replaceAll(/^-+|-+$/g, "");

	return normalized || "figma-page";
}

function toPascalCase(value) {
	return (
		String(value || "")
			.split(/[^a-z0-9]+/gi)
			.filter(Boolean)
			.map((token) => token.charAt(0).toUpperCase() + token.slice(1).toLowerCase())
			.join("") || "FigmaPage"
	);
}

function derivePageTitle(figmaUrl) {
	try {
		const url = new URL(figmaUrl);
		const parts = url.pathname.split("/").filter(Boolean);
		const rawTitle = parts[2] || parts.at(-1) || "Figma Page";
		return decodeURIComponent(rawTitle);
	} catch {
		return "Figma Page";
	}
}

function derivePageName(pageName, pageTitle, figmaUrl) {
	if (pageName) {
		return pageName;
	}

	return toPascalCase(pageTitle || derivePageTitle(figmaUrl));
}

function deriveBundlePath(args) {
	if (args.bundleFile) {
		return path.resolve(args.bundleFile);
	}

	if (!args.projectDir || !args.figmaUrl) {
		throw new Error("必须提供 --bundle-file,或者同时提供 --project-dir 与 --figma-url");
	}

	const projectDir = path.resolve(args.projectDir);
	const pageSlug = slugify(derivePageName(args.pageName, args.pageTitle, args.figmaUrl));
	const outputDir = args.outputDir ? path.resolve(args.outputDir) : path.join(projectDir, ".ai-direct", pageSlug);

	return path.join(outputDir, `${pageSlug}.ai-direct-context-bundle.json`);
}

function ensureBundle(args, bundlePath) {
	if (fileExists(bundlePath)) {
		return;
	}

	if (!args.projectDir || !args.figmaUrl) {
		throw new Error(`找不到 bundle 文件: ${bundlePath}`);
	}

	const commandArgs = [
		path.join(repoRoot, "scripts", "ai-direct-context.mjs"),
		"--project-dir",
		path.resolve(args.projectDir),
		"--figma-url",
		args.figmaUrl,
	];

	if (args.pageName) {
		commandArgs.push("--page-name", args.pageName);
	}
	if (args.pageTitle) {
		commandArgs.push("--page-title", args.pageTitle);
	}
	if (args.outputDir) {
		commandArgs.push("--output-dir", path.resolve(args.outputDir));
	}
	if (args.withoutVariables) {
		commandArgs.push("--without-variables");
	}

	child_process.execFileSync(process.execPath, commandArgs, {
		cwd: repoRoot,
		stdio: "inherit",
	});
}

function resolveArtifactPath(bundleDir, targetPath) {
	if (!targetPath) {
		return "";
	}

	return path.isAbsolute(targetPath) ? targetPath : path.resolve(bundleDir, targetPath);
}

function readAiGenerationRules() {
	const rulesPath = path.join(repoRoot, "docs", "ai", "code-generation-rules.md");
	if (fs.existsSync(rulesPath)) {
		return fs.readFileSync(rulesPath, "utf8").trim();
	}
	return "";
}

function readAiAntiPatterns() {
	const registryPath = path.join(repoRoot, "docs", "ai", "ai-anti-patterns.md");
	if (!fs.existsSync(registryPath)) return [];

	const content = fs.readFileSync(registryPath, "utf8");
	const entries = [];
	const blockRegex = /---\r?\n\{[\s\S]*?\}\r?\n---/g;
	let match;

	while ((match = blockRegex.exec(content)) !== null) {
		const jsonMatch = match[0].match(/\{[\s\S]*?\}/);
		if (!jsonMatch) continue;
		try {
			const normalized = jsonMatch[0].replaceAll(/,\s*([}\]])/g, "$1");
			entries.push(JSON.parse(normalized));
		} catch { /* skip malformed */ }
	}

	return entries;
}

function readExistingViewsStructure(projectDir) {
	if (!projectDir) return "";

	const viewsDir = path.join(projectDir, "src", "views");
	if (!fs.existsSync(viewsDir)) return "";

	// 轻量模式:只收集文件路径,不读文件内容
	const files = [];
	const walkDir = (dir, prefix = "") => {
		const entries = fs.readdirSync(dir, { withFileTypes: true });
		for (const entry of entries) {
			if (entry.isDirectory()) {
				walkDir(path.join(dir, entry.name), `${prefix}${entry.name}/`);
			} else if (entry.name.endsWith(".vue") || entry.name.endsWith(".tsx")) {
				files.push(`${prefix}${entry.name}`);
			}
		}
	};

	walkDir(viewsDir);

	if (files.length === 0) return "";

	return [
		"## 已有页面文件(追加模式)",
		`当前项目 src/views/ 下已有 ${files.length} 个文件:`,
		"",
		...files.map(f => `- src/views/${f}`),
		"",
		"### 追加模式约束",
		"1. 新生成的文件**不要**与上述文件使用相同的文件名",
		"2. 路由文件(src/router.ts)由管线自动管理,**不要**输出路由文件",
		"",
	].join("\n");
}

function buildSystemPrompt(bundle, appendContext = "") {
	const preferredVui = bundle.rules.preferredVuiPackage || "VUI";
	const fallbackChain = (bundle.rules.fallbackPackages || []).join(" -> ") || "none";
	const previewPolicy = bundle.rules.previewProjectPolicy || {};
	const componentSelection = bundle.rules.componentSelection || [];
	const generationConstraints = bundle.rules.generationConstraints || [];
	const validationGoals = bundle.rules.validationGoals || [];
	const aiRulesDoc = readAiGenerationRules();

	const parts = [
		"你是 Venus AI 页面生成代理。",
		"你的任务是根据 Figma 原始设计上下文、项目事实源和组件规则,直接生成可落地的页面代码。",
		"",
		"## 当前项目上下文",
		`- VUI 首选包: ${preferredVui}`,
		`- 降级链: ${fallbackChain}`,
		`- CLI 模板: ${previewPolicy.cliTemplate || "auto"}`,
		`- mustUseVenusCli: ${String(previewPolicy.mustUseVenusCli)}`,
		"",
		"## 组件选择约束",
		...componentSelection.map((item, index) => `${index + 1}. ${item}`),
		"",
		"## 生成约束",
		...generationConstraints.map((item, index) => `${index + 1}. ${item}`),
		"",
		"## 最终裁决目标",
		...validationGoals.map((item, index) => `${index + 1}. ${item}`),
		"",
	];

	// 追加模式:注入已有页面结构
	if (appendContext) {
		parts.push(appendContext, "");
	}

	parts.push(
		"---",
		"",
		"以下是仓库级 AI 生成规则文档,你生成的每一行代码都会被这些规则校验。",
		"",
		aiRulesDoc,
		"",
		"---",
		"",
		"## ⚠ 输出格式强制要求(违反则视为失败)",
		"",
		"你必须输出结构化 JSON,**禁止**输出解释性前缀或 Markdown。",
		"",
		"### 输出 JSON 结构",
		"```json",
		"{",
		'  "summary": "string(简要描述生成内容)",',
		'  "dependencyPlan": {',
		'    "needsDependencyChange": true,',
		'    "packages": ["string"],',
		'    "reason": "string"',
		"  },",
		'  "previewProject": {',
		'    "mustUseVenusCli": true,',
		'    "recommendedCommand": "string"',
		"  },",
		'  "files": [',
		'    { "path": "string", "language": "vue|tsx|ts|js|css|json|md", "purpose": "string", "content": "string(完整代码)" }',
		"  ],",
		'  "notes": ["string"],',
		'  "validationChecklist": ["string"]',
		"}",
		"```",
		"",
		"### files 数组约束",
		"- **files 数组必须非空**:至少包含 1 个文件对象",
		"- **每个文件必须包含完整代码**:content 字段必须是可执行的完整代码,不能是占位符或描述",
		"- **禁止返回空 files 或仅返回 summary**:如果 files 为空数组,系统将视为生成失败",
		"- **即使 design context 很小,也必须生成代码**:不要以 summary 替代代码生成",
		"",
		"### 错误示例(禁止)",
		"```json",
		'{ "summary": "生成导航栏组件..." }',
		"// 缺少 files 数组,系统会拒绝",
		"```",
		"",
		"### 正确示例",
		"```json",
		"{",
		'  "summary": "生成导航栏组件",',
		'  "files": [{ "path": "src/views/cc/components/NavBar.vue", "language": "vue", "purpose": "顶部导航栏", "content": "<template>...</template>" }]',
		"}",
		"```"
	);

	return parts.join("\n");
}

/**
 * 从 VUI 组件目录中构建"场景→组件"快速映射表
 * 这是让 AI 快速匹配设计场景到 VUI 组件的关键机制
 *
 * @param {object} bundle - 完整的 context bundle
 * @returns {string} 格式化的场景映射表文本
 */
function buildScenarioComponentMap(bundle) {
	const components = bundle.componentFacts?.vuiCatalog?.components || [];
	if (components.length === 0) {
		return "";
	}

	const lines = [
		"# ⚠ VUI 组件场景匹配表(必须遵守)",
		"",
		"**以下映射表从组件 manifest 自动提取。当设计稿中出现表中描述的场景时,必须使用对应的 VUI 组件,禁止用原生 div/span 替代。**",
		"",
	];

	for (const component of components) {
		const name = component.exportName;
		const scenarios = component.usageGuidance?.recommendedScenarios || [];
		const keywords = component.figmaMapping?.keywords || [];
		const avoids = component.usageGuidance?.avoidScenarios || [];
		const antiPatterns = component.usageGuidance?.antiPatterns || [];
		const description = component.description || "";
		const codeExample = component.codeExample || "";

		// 只输出有场景定义的组件
		if (scenarios.length === 0 && keywords.length === 0) {
			continue;
		}

		// 精简描述(取第一句话)
		const shortDesc = description.split(/[。,,.]/)[0].trim().slice(0, 80);

		lines.push(`## ${name}`, `> ${shortDesc}`, "");

		if (scenarios.length > 0) {
			lines.push("**适用场景**(看到这些设计模式时必须使用该组件):");
			for (const s of scenarios) {
				lines.push(`- ${s}`);
			}
			lines.push("");
		}

		if (keywords.length > 0) {
			lines.push(`**Figma 关键词**: ${keywords.join(", ")}`, "");
		}

		if (avoids.length > 0) {
			lines.push(`**不适用**: ${avoids.join("; ")}`, "");
		}

		if (antiPatterns.length > 0) {
			lines.push("**⛔ 反模式(禁止以下写法)**:", "```", ...antiPatterns.map((p) => `✗ ${p}`), "```", "");
		}

		if (codeExample) {
			lines.push("**代码示例**(直接参考此用法):", "```vue", codeExample, "```", "");
		}
	}

	lines.push("---", "");

	return lines.join("\n");
}

function buildUserPrompt({ bundle, promptText, designContext, variableDefsText, singlePageMode }) {
	const compactBundle = buildPromptBundleSnapshot(bundle);
	const compactDesignContext = buildPromptDesignContext(bundle, designContext);
	const primaryFacts = extractPrimaryFigmaFacts(designContext);
	const scenarioMap = buildScenarioComponentMap(bundle);

	// 检测多模块模式:合并的设计上下文包含 "### === Module:" 标记
	const moduleMarkers = designContext.match(/### === Module:/g) || [];
	const isMultiModule = moduleMarkers.length > 1;

	const sections = [
		"# Task Context",
		promptText.trim(),
		"",
	];

	// 场景→组件映射表:放在 Bundle JSON 之前,确保 AI 优先看到
	if (scenarioMap) {
		sections.push(scenarioMap);
	}

	sections.push(
		"# Bundle Snapshot",
		JSON.stringify(compactBundle, null, 2),
		"",
		"# Figma Design Context",
		compactDesignContext,
		"",
		"# Primary Figma Facts",
		JSON.stringify(primaryFacts, null, 2),
		"",
		"# Figma 布局解读指南",
		"",
		"从 Figma Design Context YAML 中解读布局时,请遵循以下规则:",
		"",
		"1. **GROUP vs FRAME 语义**:",
		"   - `FRAME` 类型通常有明确布局(Auto Layout),关注 `layout` 字段中的 `overflow`、`direction` 等",
		"   - `GROUP` 类型是绝对定位组合,子元素的位置由 Figma 画布坐标决定,不代表 flex 布局",
		"   - 当 GROUP 的子元素在截图中呈横向排列时,应使用 `display: flex; flex-direction: row` 或 `grid`",
		"",
		"2. **位置推断**:",
		"   - 如果截图中某元素在容器的角落(如左上角、右下角),使用 `position: absolute` + 对应方位定位",
		"   - 如果截图中多个元素在同一行,使用 flex row 布局而非 absolute 定位",
		"   - 设计稿中 `opacity` < 1 的元素通常是叠加层(overlay),需使用 absolute 定位",
		"",
		"3. **层级关系**:",
		"   - YAML 中同级 children 的顺序不代表视觉层级,只代表 DOM 顺序",
		"   - 绝对定位元素(如浮动按钮、角标)应在 YAML 树中独立于内容流之外",
		"   - 倒计时、价格标签等同区域元素应判断是同行(flex row)还是分行(各自占满宽度)",
		"",
		"4. **尺寸与间距**:",
		"   - `fontSize`、`lineHeight`、`letterSpacing` 直接使用设计稿数值",
		"   - `gap`、`padding` 从 Figma Auto Layout 数据推断,若无明确数据则使用合理默认值(8px/12px/16px)",
		"   - `radius` 数组 `[tl, tr, br, bl]` 对应 CSS border-radius 四个角",
		"",
		"# Variable Definitions",
		variableDefsText || "{}",
		"",
	);

	// 生成模式:单页面模式 vs 组件模式
	const pageName = compactBundle.figma?.pageName || "FigmaPage";
	const pageDir = `src/views/${pageName}`;
	const componentBaseDir = `${pageDir}/components`;
	const toolsDir = `${pageDir}/tools`;

	// 页面目录结构规范(适用于所有模式)
	sections.push(
		"# 页面目录结构规范",
		"",
		`每个页面必须遵循以下目录结构(\`${pageDir}/\`):`,
		"",
		"```",
		`${pageDir}/`,
		`  index.vue          # 页面入口(组合页或完整页面)`,
		`  components/*.vue   # 子组件`,
		`  tools/*.ts         # 页面级工具函数(hooks、utils、types)`,
		"```",
		"",
		"- `index.vue` 是页面入口,由管线自动注册路由",
		"- `components/` 存放子组件,单页面模式下可不用",
		"- `tools/` 存放页面级工具函数,如有 composable hooks 或类型定义请放这里",
		"- **禁止**在 `src/views/` 下直接放置 `*.vue` 文件(如 `src/views/PageName.vue`)",
		"",
		"",
	);

	if (singlePageMode) {
		// 单 URL 模式:直接生成页面入口文件
		const pageFilePath = `${pageDir}/index.vue`;
		sections.push(
			"# ⚠ 单页面生成模式(重要)",
			"",
			"当前只有一个 Figma URL,直接生成一个完整的页面文件。",
			"",
			"**你必须:**",
			`1. 生成**一个**完整的 Vue 页面文件,路径为 \`${pageFilePath}\``,
			"2. 页面文件应包含该设计稿中所有内容(导航栏、内容区、底部栏等),整合在一个 Vue SFC 中",
			"3. **不要**拆分成多个组件文件",
			"",
			"示例输出结构:",
			"```",
			"files: [",
			`  { "path": "${pageFilePath}", ... }`,
			"]",
			"```",
			"",
		);
	} else {
		// 多 URL 模式:每个 URL 生成一个组件到 components/ 下
		if (isMultiModule) {
			sections.push(
				"# ⚠ 多区块组件生成模式(重要)",
				"",
				`当前 Figma Design Context 包含 **${moduleMarkers.length} 个页面区块**,每个区块以 \`### === Module: <URL> ===\` 标记分隔。`,
				"",
				"每个区块代表**同一页面的不同部分**(如导航栏、列表、详情、价格区域等)。",
				"",
				"**你必须:**",
				`1. 为**每个区块**生成一个独立的 Vue 组件文件,放在 \`${componentBaseDir}/\` 目录下`,
				"2. 组件命名规则(PascalCase):",
				"   - 优先从 Figma 页面/节点标题推导,如标题为 `Car Detail` → `CarDetail.vue`",
				"   - 若 Figma 标题无意义(如 `Node640708`、`Frame 1`、`Group 3` 等纯 ID/序号),则根据该区块的**实际内容**归纳一个语义化名称,例如:包含商品列表 → `ProductList.vue`,包含用户信息表单 → `UserProfileForm.vue`,包含价格摘要 → `PriceSummary.vue`",
				"   - **禁止**使用 `Node` + 数字、`Frame` + 数字、`Group` + 数字、`FigmaPage`、`index` 等无意义名称",
				"3. **不要**生成父页面或 index.vue — 管线会在所有批次完成后自动生成组合页",
				"4. **不要**只生成第一个区块而忽略其他区块",
				"5. 每个组件只包含对应区块的 UI、逻辑和样式",
				"",
				"示例输出结构:",
				"```",
				"files: [",
				`  { "path": "${componentBaseDir}/CarDetail.vue", ... },`,
				`  { "path": "${componentBaseDir}/CarList.vue", ... },`,
				`  { "path": "${componentBaseDir}/PriceSection.vue", ... }`,
				"]",
				"```",
				"",
			);
		} else {
			sections.push(
				"# ⚠ 单组件生成模式(重要)",
				"",
				`当前 Figma Design Context 对应**一个页面区块**(属于多 URL 批次中的一批)。`,
				"",
				"**你必须:**",
				`1. 生成**一个** Vue 组件文件,路径为 \`${componentBaseDir}/<ComponentName>.vue\``,
				"2. 组件命名规则(PascalCase):",
				"   - 优先从 Figma 页面/节点标题推导,如标题为 `Price Section` → `PriceSection.vue`",
				"   - 若 Figma 标题无意义(如 `Node640708`、`Frame 1`、`Group 3` 等纯 ID/序号),则根据该组件的**实际内容**归纳一个语义化名称,例如:包含商品详情 → `ProductDetail.vue`,包含搜索栏 → `SearchBar.vue`",
				"   - **禁止**使用 `Node` + 数字、`Frame` + 数字、`Group` + 数字、`FigmaPage`、`index` 等无意义名称",
				"3. **不要**生成父页面或 index.vue — 管线会在所有批次完成后自动生成组合页",
				"",
				"示例输出结构:",
				"```",
				"files: [",
				`  { "path": "${componentBaseDir}/CarDetail.vue", ... }`,
				"]",
				"```",
				"",
			);
		}
	}

	sections.push(
		"# ⚠ 生成策略:无条件生成 + 系统元素过滤(最重要)",
		"",
		"## 核心原则:你必须无条件生成代码",
		"",
		"我提供的每个 Figma URL 都经过筛选,**全部包含有意义的业务内容**。",
		"**无论 design context 看起来多么简单、多么像系统元素,你都必须生成 files[] 代码。**",
		"",
		"常见场景与正确做法:",
		"- 节点只包含一个导航栏 → 用 VNavBar 组件生成,设置 title 和 leftArrow 等 props",
		"- 节点只包含一个按钮 → 用 VButton 组件生成",
		"- 节点只包含一个搜索框 → 用 VSearch 组件生成",
		"- 节点包含状态栏 + 导航栏 → 跳过状态栏,只生成导航栏(VNavBar)",
		"- design context 字符数很少 → 仍然必须生成代码,不要返回 summary",
		"",
		"## 生成时过滤系统级示意图元素",
		"",
		"在生成组件代码时,以下系统级示意图元素**不需要**出现在代码中,直接忽略即可:",
		"- 状态栏(Status Bar):时间显示(9:41)、信号图标、WiFi 图标、电池图标",
		"- 导航栏中的系统图标:返回箭头(用组件的 leftArrow prop 代替)、更多按钮(...)图标",
		"- 小程序导航栏右侧胶囊按钮(Capsule Button)",
		"- 底部安全区(Safe Area):iPhone 底部横条",
		"- **底部标签栏(TabBar)**:name 为\"底部标签栏\"或包含多个全局导航项(如\"首页/我的\"等)的 FRAME/GROUP。底部标签栏是应用级全局导航,由应用骨架提供,**不要在页面中生成**",
		"- 系统键盘、系统弹窗、系统提示框等操作系统 UI",
		"",
		"这些元素不需要生成代码,但它们**不构成拒绝生成的理由**——你仍然必须生成包含业务组件(如 VNavBar)的完整代码。",
		"",
		"## ⚠ 禁止的响应格式",
		"",
		"- **禁止**返回 `{\"summary\": \"...\"}` 格式代替代码",
		"- **禁止**返回空的 files 数组 `\"files\": []`",
		"- **禁止**以任何理由(节点太简单、只有系统元素、design context 太小等)拒绝生成",
		"",
		"你必须始终返回包含 files 数组的 JSON,其中至少包含一个 .vue 组件文件。",
		"",
		"",
		"# 布局推断规则(重要)",
		"",
		"Design Context 不包含 flex/grid 布局方向信息,你需要根据 UI 元素的语义和上下文正确推断布局。",
		"以下是常见场景的布局推断规则:",
		"",
		"## 1. 横向并排标签/页签",
		"- 同级 TEXT 节点如果是简短的标签文本(如\"本地精选\"、\"猜你喜欢\"),且字号/颜色不同表示选中/未选中状态 → 它们是**横向并排的 Tab 页签**",
		"- 用 `display: flex; flex-direction: row; gap: Xpx;` 实现",
		"- **不要**把它们拆成两个独立的纵向 section",
		"",
		"## 2. 卡片列表方向(纵向 vs 横向)",
		"- 移动端页面中的内容卡片(商品卡片、车辆卡片、文章卡片等),如果卡片内包含图片+文本信息 → **默认使用纵向布局**:图片在上方,文字信息在下方",
		"- 卡片内图片(RECTANGLE + IMAGE background)应使用 `width: 100%; height: 固定高度;` 铺满卡片宽度",
		"- **不要**默认把卡片做成左图右文的横向布局(除非 design context 明确指示)",
		"",
		"## 3. 列表列数(重要:移动端默认 2 列)",
		"- **移动端页面中,所有列表数据默认使用 2 列网格布局**:`display: grid; grid-template-columns: 1fr 1fr; gap: Xpx;`",
		"- 无论是卡片列表(图片+文字)、文字列表(key:value)、还是纯文本列表,都默认 2 列",
		"- **不要**使用 `flex-direction: column` 做 1 列纵向列表",
		"- 只有在 design context 中有明确的「全宽卡片」结构(单个卡片占满整行宽度)时,才可以例外使用 1 列",
		"",
		"## 4. 标签/筛选条件换行",
		"- 同级 TEXT 节点如果是多个短标签(如筛选条件:SUV、轿车、新能源...)→ 使用 `flex-wrap: wrap;` 允许换行",
		"- **不要**使用 `overflow-x: auto` 做横向滚动,除非标签数量很少且 design context 暗示是横向滚动",
		"- 标签容器的 gap 通常较小(4-8px),每个标签使用固定 padding",
		"",
		"## 5. 禁止臆造设计稿中不存在的内容",
		"",
		"**你只能生成 design context 中明确存在的 UI 元素。** 每个生成的区块都必须能在 design context 中找到对应的节点。",
		"",
		"**禁止:**",
		"- 生成 design context 中不存在的 section(如凭空添加\"热搜品牌\"、\"推荐列表\"等)",
		"- 为 design context 中的元素添加不存在的子组件(如给卡片添加不存在的\"收藏\"按钮)",
		"- 合并或拆分 design context 中的结构(如把两个独立 section 合并成一个)",
		"",
		"**自检方法**:生成代码后,逐一检查每个 section/模块,确认它是否能在 design context 中找到对应的 FRAME/GROUP/TEXT 节点。如果找不到,删除该部分代码。",
		"",
		"",

	);

	// 短 design context 检测:内容极少时注入强化指令,防止 AI 只返回 summary
	const designContextLength = compactDesignContext.length;
	if (designContextLength < 2500) {
		sections.push(
			`# ⚠ 当前 Design Context 非常短(约 ${designContextLength} 字符)`,
			"",
			"这意味着 Figma 节点内容较少(如单个按钮、导航栏、操作栏等),但**你仍然必须生成完整的 Vue SFC 代码**。",
			"",
			"**正确做法**:根据节点中可见的 UI 元素,使用对应的 VUI 组件生成代码。例如:",
			"- 看到一个按钮 → 用 VButton 生成",
			"- 看到导航栏 → 用 VNavBar 生成(title 取自 design context 中的文本)",
			"- 看到底部操作栏 → 用 VButton 或 div + 样式生成固定底部栏",
			"- 看到搜索框 → 用 VSearch 生成",
			"",
			"**错误做法(会导致失败)**:只返回 `{\"summary\": \"...\"}` 而没有 files 数组。",
			"",
			"",
		);
	}

	sections.push(
		"# Instructions",
		singlePageMode
			? `- 基于以上 Figma 设计上下文,生成一个完整的页面文件到 \`src/views/\` 目录。`
			: (isMultiModule
				? `- 基于以上**所有区块**的 Figma 设计上下文,为每个区块生成一个独立组件到 \`${componentBaseDir}/\` 目录。`
				: `- 基于以上 Figma 设计上下文,生成一个组件到 \`${componentBaseDir}/\` 目录。`),
		"- 如果需要新增 @vui/* 依赖,必须在 dependencyPlan 中明确说明。",
		"- files 内的路径必须相对目标项目根目录。",
		"- 如果生成的是预览项目页面,文件路径应匹配 Venus CLI 创建出的项目结构。",
		"- Vue 页面必须按仓库 lint 友好的格式输出,尤其避免 indent、quotes、semi、perfectionist/sort-imports、perfectionist/sort-named-imports、vue/html-indent、vue/first-attribute-linebreak、vue/attributes-order 违规。",
		"- 若使用多行组件属性,请保持首属性与标签名同行,并做到每行一个属性,事件放在靠后位置。",
		"- 如无法确认某个 VUI 组件的 props 细节,优先保持组件合法、结构简洁,不要为了追求还原度写出高风险属性组合。",
		"- 页面级样式必须直接在本次生成文件中给出;不要假设我会再去其他目标产物里手工补样式。",
		"- 若生成 Vue 页面,请在页面文件中包含 `<style>`,并让页面在中性骨架下也具备完整布局和基本视觉层次。",
		"- 请优先参考 design context 中可直接读取的布局与视觉参数,尽量还原真实的间距、分栏、输入控件宽度、表头层次与分页位置。",
		"- 当 Figma 原始 design context、显式文本节点、placeholder、列名、示例数据与截图摘要发生冲突时,始终以 Figma 原始数据和组件事实源为准,截图只用于辅助校正视觉分组、留白、颜色和分页对齐。",
		"- 如果 Figma 原始数据中存在工具栏标签与输入框 placeholder,必须完整保留,不要因为截图理解偏差而省略。",
		"- 工具栏控件顺序必须与设计稿保持一致,不要把按钮挪到筛选区或标题区之外。",
		"- 工具栏搜索控件应与 Figma 设计稿中的控件类型保持一致。",
		"- 如果 Figma 原始数据中存在表格示例内容,预览页必须生成非空示例数据,并优先复用这些文本线索,而不是输出空表格。",
		"- 表格布局应忠实设计稿:设计稿中表格横向铺满容器时,让表格和其外层容器撑满可用空间;列宽按设计稿指定,设计稿未指定的列由组件自动分配,不要给所有列都硬编码固定 width。",
		"- 表格、分页器、筛选控件等组件的视觉样式(背景色、对齐方式、激活态样式等)必须按设计稿如实还原;设计稿中没有的样式不要自行添加。",
		"- 若设计稿中某些元素同属一个容器(例如标题与工具栏在同一个 justify: space-between 容器内),生成代码必须保留这种父子关系,不要把同一个容器的子元素拆成多个独立 div。",
		"- 如果设计稿里没有某些装饰信息,不要自行添加设计稿中不存在的装饰元素。",
		"- 传给表格组件的 columns 类型必须与目标组件兼容,尤其 `align` 只能使用合法联合字面量,而不是宽泛字符串。",
		"- 禁止输出路由文件(src/router.ts 或 src/router/index.ts)。模板已提供路由文件,管线会自动扫描 views 目录并注入路由。你只需生成页面组件。",

	);

	return sections.join("\n");
}

function collectDesignContextTexts(designContext) {
	const lines = String(designContext || "").split(/\r?\n/u);
	const texts = [];

	for (let index = 0; index < lines.length; index++) {
		const line = lines[index];
		const match = line.match(/^(\s*)text:\s*(.*)$/u);
		if (!match) {
			continue;
		}

		const baseIndent = match[1].length;
		const rawValue = match[2].trim();
		if (rawValue === "|-" || rawValue === "|") {
			const blockLines = [];
			let cursor = index + 1;
			while (cursor < lines.length) {
				const nextLine = lines[cursor];
				if (!nextLine.trim()) {
					blockLines.push("");
					cursor++;
					continue;
				}

				const nextMatch = nextLine.match(/^(\s+)(.*)$/u);
				if (!nextMatch || nextMatch[1].length <= baseIndent) {
					break;
				}

				if (nextMatch[2] || blockLines.length > 0) {
					blockLines.push(nextMatch[2].trimEnd());
				}
				cursor++;
			}

			const blockText = blockLines.join("\n").trim();
			if (blockText) {
				texts.push(blockText);
			}
			index = cursor - 1;
			continue;
		}

		if (rawValue) {
			texts.push(rawValue.replaceAll(/^['"]|['"]$/gu, "").trim());
		}
	}

	return [...new Set(texts.map((item) => item.trim()).filter(Boolean))];
}

function extractPrimaryFigmaFacts(designContext) {
	const texts = collectDesignContextTexts(designContext);
	const normalizedTexts = new Set(texts.map((item) => item.replace(/[::]$/u, "")));

	const designContextText = String(designContext || "");

	// 从 design context 动态检测视觉属性,而非硬编码
	// 检测表格表头背景色:匹配任意表头文本后的 background 属性
	const firstColumnName = texts.find((item) => /^(序号|编号|ID|序号列|名称)$/u.test(item)) || "序号";
	const detectedTableHeaderBg = detectColorProperty(designContextText, new RegExp(`${firstColumnName}[\\s\\S]{0,400}?background:\\s*rgba\\((\\d+),\\s*(\\d+),\\s*(\\d+)`, "u"));
	const detectedPaginationAlign = detectPaginationAlignment(designContextText);
	const detectedTableFillWidth = new RegExp(`name:\\s*${firstColumnName}[\\s\\S]*?sizingH:\\s*fill`, "u").test(designContextText) || new RegExp(`sizingH:\\s*fill[\\s\\S]*?name:\\s*${firstColumnName}`, "u").test(designContextText);
	const hasToolbarJustifyBetween = /justify:\s*space-between/u.test(designContextText);
	const selectContainerWidth = extractFigmaDimension(designContextText, "输入框", "w");
	const selectInnerWidth = extractFigmaInnerSelectWidth(designContextText);

	// 占位符、按钮文案等从设计文本中动态提取
	const placeholderText = texts.find((item) => /请输入/u.test(item)) || "";
	// 动态检测查询/提交按钮:匹配常见的操作按钮文案
	const queryButtonLabel = texts.find((item) => /^(查询|搜索|确认|提交|重置|确定|取消|导出|导入|新增|删除|编辑)$/u.test(item)) || "";

	return {
		textsFromDesign: texts.slice(0, 30),
		toolbarHasJustifyBetween: hasToolbarJustifyBetween,
		selectContainerWidth,
		selectInnerWidth,
		placeholderText,
		queryButtonLabel,
		// 以下为动态检测的视觉属性,空值表示设计中未检测到该特征
		tableHeaderBackground: detectedTableHeaderBg,
		tableShouldFillWidth: detectedTableFillWidth,
		paginationAlignment: detectedPaginationAlign,
	};
}

function detectColorProperty(designContext, pattern) {
	const match = designContext.match(pattern);
	if (!match) {
		return "";
	}
	const r = Number.parseInt(match[1], 10);
	const g = Number.parseInt(match[2], 10);
	const b = Number.parseInt(match[3], 10);
	// 只返回明显的非白色背景
	if (r > 240 && g > 240 && b > 240) {
		return "";
	}
	return `rgb(${r}, ${g}, ${b})`;
}

function detectPaginationAlignment(designContext) {
	if (/分页[\s\S]{0,200}?justify:\s*(center|flex-end|space-between)/u.test(designContext)) {
		return "non-left";
	}
	if (/pagination[\s\S]{0,200}?justify:\s*(center|flex-end|space-between)/u.test(designContext)) {
		return "non-left";
	}
	return "";
}

function extractFigmaDimension(designContext, containerName, prop) {
	const pattern = new RegExp(`name:\\s*${containerName}[\\s\\S]*?${prop}-\\[(\\d+)px\\]`, "u");
	const match = designContext.match(pattern);
	return match ? Number.parseInt(match[1], 10) : 0;
}

function extractFigmaInnerSelectWidth(designContext) {
	const inputInstances = designContext.match(/name:\s*输入框[\s\S]*?w-\[(\d+)px\]/gu);
	if (!inputInstances) {
		return 0;
	}

	for (const instance of inputInstances) {
		const innerMatch = instance.match(/画板\s*1[\s\S]*?w-\[(\d+)px\]/u);
		if (innerMatch) {
			return Number.parseInt(innerMatch[1], 10);
		}
	}

	return 0;
}

function buildPromptBundleSnapshot(bundle) {
	const workspacePackageExports = (bundle.projectUi?.workspacePackageExports || []).map((item) => ({
		packageName: item.packageName,
		exportNames: item.exportNames || [],
	}));
	const availableVuiExports = (bundle.componentFacts?.vuiCatalog?.components || []).map((component) => component.exportName);
	const vuiComponentSignatures = (bundle.componentFacts?.vuiCatalog?.components || []).map((component) => ({
		exportName: component.exportName,
		description: component.description || "",
		semanticRoles: component.semanticRoles || [],
		supportedKinds: component.supportedKinds || [],
		priority: component.priority,
		props: (component.props || []).map((prop) => ({
			name: prop.name,
			type: prop.type,
			description: prop.description || undefined,
			default: prop.default,
		})),
		events: (component.events || []).map((event) => ({
			name: event.name,
			description: event.description || undefined,
			payload: event.payload || undefined,
		})),
		slots: (component.slots || []).map((slot) => ({
			name: slot.name,
			description: slot.description || undefined,
			scope: slot.scope || undefined,
		})),
		figmaMapping: component.figmaMapping || undefined,
		usageGuidance: component.usageGuidance || undefined,
	}));

	return {
		figma: {
			figmaUrl: bundle.figma?.figmaUrl || "",
			pageName: bundle.figma?.pageName || "",
			pageTitle: bundle.figma?.pageTitle || "",
			pageSlug: bundle.figma?.pageSlug || "",
			designContextExcerpt: String(bundle.figma?.designContextExcerpt || "").slice(0, 2000),
		},
		projectContext: {
			projectName: bundle.projectContext?.projectName || "",
			framework: bundle.projectContext?.framework || "",
			appType: bundle.projectContext?.appType || "",
			pageDirs: bundle.projectContext?.directories?.pageDirs || [],
			routeFiles: bundle.projectContext?.directories?.routeFiles || [],
			existingPages: bundle.projectContext?.existingPages?.pages || [],
			uiStack: bundle.projectContext?.uiStack || {},
			constraints: bundle.projectContext?.constraints || [],
		},
		projectUi: {
			projectInstalledPackages: bundle.projectUi?.projectInstalledPackages || [],
			workspacePackageExports,
		},
		componentSelection: {
			preferredPackages: bundle.componentFacts?.preferredPackages || [],
			fallbackPackages: bundle.componentFacts?.fallbackPackages || [],
			availableVuiExports,
			vuiComponentSignatures,
		},
		rules: {
			framework: bundle.rules?.framework || "",
			preferredVuiPackage: bundle.rules?.preferredVuiPackage || "",
			fallbackPackages: bundle.rules?.fallbackPackages || [],
			previewProjectPolicy: bundle.rules?.previewProjectPolicy || {},
			componentSelection: bundle.rules?.componentSelection || [],
			generationConstraints: bundle.rules?.generationConstraints || [],
			validationGoals: bundle.rules?.validationGoals || [],
		},
		artifacts: {
			designContextFile: bundle.artifacts?.designContextFile || "",
			variableDefsFile: bundle.artifacts?.variableDefsFile || "",
			screenshotFile: bundle.artifacts?.screenshotFile || "",
			screenshotSummaryFile: bundle.artifacts?.screenshotSummaryFile || "",
		},
	};
}

function buildPromptDesignContext(bundle, designContext) {
	const trimmed = String(designContext || "").trim();
	if (!trimmed) {
		return String(bundle.figma?.designContextExcerpt || "").slice(0, 2000);
	}

	return trimmed;
}

function resolveScreenshotMimeType(screenshotFilePath) {
	const extension = path.extname(screenshotFilePath).toLowerCase();
	if (extension === ".jpg" || extension === ".jpeg") {
		return "image/jpeg";
	}
	if (extension === ".webp") {
		return "image/webp";
	}
	return "image/png";
}

function extractJsonPayload(text) {
	const trimmed = String(text || "").trim();
	if (!trimmed) {
		throw new Error("视觉摘要返回为空");
	}

	try {
		return JSON.parse(trimmed);
	} catch {}

	const fencedMatch = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i);
	if (fencedMatch) {
		return JSON.parse(fencedMatch[1].trim());
	}

	const start = trimmed.indexOf("{");
	const end = trimmed.lastIndexOf("}");
	if (start !== -1 && end !== -1 && end > start) {
		return JSON.parse(trimmed.slice(start, end + 1));
	}

	throw new Error("无法从视觉摘要返回中提取 JSON");
}

function normalizeVisualSummary(summary) {
	if (!summary || typeof summary !== "object") {
		return null;
	}

	const pageType = typeof summary.pageType === "string" ? summary.pageType : "desktop";

	return {
		pageType,
		layoutOrder: Array.isArray(summary.layoutOrder) ? summary.layoutOrder.filter(Boolean) : [],
		pageCategory: typeof summary.pageCategory === "string" ? summary.pageCategory : "",
		filterGroupLabels: Array.isArray(summary.filterGroupLabels) ? summary.filterGroupLabels.filter(Boolean) : [],
		requiredSelectCount: Number(summary.requiredSelectCount) || 0,
		headerTitle: typeof summary.headerTitle === "string" ? summary.headerTitle : "",
		searchLabel: typeof summary.searchLabel === "string" ? summary.searchLabel : "",
		primaryActionLabel: typeof summary.primaryActionLabel === "string" ? summary.primaryActionLabel : "",
		tableColumns: Array.isArray(summary.tableColumns) ? summary.tableColumns.filter(Boolean) : [],
		actionColumnLabel: typeof summary.actionColumnLabel === "string" ? summary.actionColumnLabel : "",
		actionLinkLabel: typeof summary.actionLinkLabel === "string" ? summary.actionLinkLabel : "",
		formFields: Array.isArray(summary.formFields) ? summary.formFields.filter(Boolean) : [],
		pagination: {
			present: Boolean(summary.pagination?.present),
			containerAlignment:
				typeof summary.pagination?.containerAlignment === "string" ? summary.pagination.containerAlignment : "",
			totalTextVisible: Boolean(summary.pagination?.totalTextVisible),
			pageSizeSelectorVisible: Boolean(summary.pagination?.pageSizeSelectorVisible),
			jumperVisible: Boolean(summary.pagination?.jumperVisible),
			activePageStyle: typeof summary.pagination?.activePageStyle === "string" ? summary.pagination.activePageStyle : "",
		},
		style: {
			backgroundTone: typeof summary.style?.backgroundTone === "string" ? summary.style.backgroundTone : "",
			headerTone: typeof summary.style?.headerTone === "string" ? summary.style.headerTone : "",
			primaryColor: typeof summary.style?.primaryColor === "string" ? summary.style.primaryColor : "",
		},
		// 移动端专用字段
		sectionOrder: Array.isArray(summary.sectionOrder) ? summary.sectionOrder.filter(Boolean) : [],
		sections: Array.isArray(summary.sections)
			? summary.sections.map((section) => ({
				name: typeof section.name === "string" ? section.name : "",
				description: typeof section.description === "string" ? section.description : "",
				floatingOverlays: Array.isArray(section.floatingOverlays)
					? section.floatingOverlays.map((overlay) => ({
						text: typeof overlay.text === "string" ? overlay.text : "",
						position: typeof overlay.position === "string" ? overlay.position : "",
						description: typeof overlay.description === "string" ? overlay.description : "",
					}))
					: [],
			}))
			: [],
		bottomFixedBar: {
			present: Boolean(summary.bottomFixedBar?.present),
			confidence: typeof summary.bottomFixedBar?.confidence === "string" ? summary.bottomFixedBar.confidence : "high",
			primaryButtonText:
				typeof summary.bottomFixedBar?.primaryButtonText === "string" ? summary.bottomFixedBar.primaryButtonText : "",
			secondaryElements: Array.isArray(summary.bottomFixedBar?.secondaryElements)
				? summary.bottomFixedBar.secondaryElements
				: [],
		},
		sectionConfidence: summary.sectionConfidence && typeof summary.sectionConfidence === "object"
			? Object.fromEntries(
				Object.entries(summary.sectionConfidence).filter(([, v]) => typeof v === "string"),
			)
			: {},
		listLayouts: Array.isArray(summary.listLayouts)
			? summary.listLayouts.map((layout) => ({
				section: typeof layout.section === "string" ? layout.section : "",
				type: typeof layout.type === "string" ? layout.type : "",
				columns: Number(layout.columns) || 1,
				direction: typeof layout.direction === "string" ? layout.direction : "column",
				labelOnTop: Boolean(layout.labelOnTop),
				description: typeof layout.description === "string" ? layout.description : "",
			}))
			: [],
		imageLayout: {
			pattern: typeof summary.imageLayout?.pattern === "string" ? summary.imageLayout.pattern : "",
			firstImageFullWidth: Boolean(summary.imageLayout?.firstImageFullWidth),
			thumbnailColumns: Number(summary.imageLayout?.thumbnailColumns) || 1,
			description: typeof summary.imageLayout?.description === "string" ? summary.imageLayout.description : "",
		},
		priceSection: {
			countdownPosition:
				typeof summary.priceSection?.countdownPosition === "string" ? summary.priceSection.countdownPosition : "",
			countdownDescription:
				typeof summary.priceSection?.countdownDescription === "string" ? summary.priceSection.countdownDescription : "",
		},
		keyColors: Array.isArray(summary.keyColors) ? summary.keyColors.filter(Boolean) : [],
		notes: Array.isArray(summary.notes) ? summary.notes.filter(Boolean) : [],
	};
}

/**
 * 用 Figma 结构化数据交叉校验截图视觉摘要
 * Figma API 是结构化事实源,截图摘要是视觉辅助,两者冲突时以 Figma 为准
 *
 * @param {object} screenshotSummary - Vision Model 返回并 normalize 后的摘要
 * @param {object} layoutInfo - Figma extractLayoutInfo 的结果
 * @returns {object} 附加了 crossValidationWarnings 的摘要
 */
function crossValidateWithFigma(screenshotSummary, layoutInfo) {
	if (!screenshotSummary || !layoutInfo) {
		return screenshotSummary;
	}

	const warnings = [];

	// 1. bottomFixedBar 交叉校验
	const visionHasBottomBar = screenshotSummary.bottomFixedBar?.present;
	const figmaHasBottomBar = Boolean(layoutInfo.bottomBar);

	if (visionHasBottomBar && !figmaHasBottomBar) {
		screenshotSummary.bottomFixedBar.confidence = "low";
		screenshotSummary.bottomFixedBar.source = "vision-only";
		warnings.push(
			"bottomFixedBar: 截图摘要声称底部有操作栏,但 Figma 结构数据中未检测到匹配的底部固定栏(y+h 接近页面底部且宽度 ≥ 80%)。该字段可能为幻觉,代码生成时应优先检查 Figma design context 确认。",
		);
	} else if (visionHasBottomBar && figmaHasBottomBar && screenshotSummary.bottomFixedBar.confidence === "low") {
		warnings.push(
			"bottomFixedBar: Vision Model 对底部操作栏的置信度为 low,虽然 Figma 也检测到了底部栏,建议以 Figma 数据中的按钮文字为准。",
		);
	} else if (!visionHasBottomBar && figmaHasBottomBar) {
		warnings.push(
			`bottomFixedBar: Figma 结构数据检测到底部有操作栏(name="${layoutInfo.bottomBar.name}", texts=[${(layoutInfo.bottomBar.texts || []).join(", ")}]),但截图摘要未识别。请以 Figma 数据为准生成底部操作栏。`,
		);
	} else if (visionHasBottomBar && figmaHasBottomBar) {
		// 两边都有,校验按钮文字
		const figmaTexts = layoutInfo.bottomBar.texts || [];
		const visionPrimary = screenshotSummary.bottomFixedBar.primaryButtonText || "";
		if (visionPrimary && figmaTexts.length > 0 && !figmaTexts.some((t) => t.includes(visionPrimary) || visionPrimary.includes(t))) {
			warnings.push(
				`bottomFixedBar.primaryButtonText: 截图摘要说按钮文字为"${visionPrimary}",但 Figma 中底部栏文字为 [${figmaTexts.join(", ")}]。请以 Figma 文本为准。`,
			);
		}
	}

	// 2. section 数量校验
	const figmaSectionCount = (layoutInfo.sections || []).length;
	const visionSectionCount = (screenshotSummary.sections || []).length;
	if (figmaSectionCount > 0 && visionSectionCount > 0 && Math.abs(figmaSectionCount - visionSectionCount) > 2) {
		warnings.push(
			`区块数量差异较大: Figma 检测到 ${figmaSectionCount} 个垂直分区,截图摘要识别了 ${visionSectionCount} 个 section。请以 Figma 结构数据为主要参考。`,
		);
	}

	// 3. 底部栏信息补充(Figma 有但截图没识别到文字时)
	if (figmaHasBottomBar && layoutInfo.bottomBar.texts?.length > 0 && !screenshotSummary.figmaBottomBar) {
		screenshotSummary.figmaBottomBar = {
			name: layoutInfo.bottomBar.name,
			texts: layoutInfo.bottomBar.texts,
			y: layoutInfo.bottomBar.y,
			height: layoutInfo.bottomBar.height,
		};
	}

	screenshotSummary.crossValidationWarnings = warnings;
	return screenshotSummary;
}

/**
 * 从 Figma layout-info 构建先验知识,注入 Vision Model prompt
 * 让 Vision Model 有结构性参考,减少幻觉
 *
 * @param {object} layoutInfo - Figma extractLayoutInfo 的结果
 * @returns {string} 注入到 Vision prompt 的先验提示文本
 */
function buildFigmaPriorHints(layoutInfo) {
	if (!layoutInfo) {
		return "";
	}

	const hints = [
		"",
		"**以下是从 Figma 结构数据提取的先验信息,请据此验证你的视觉判断**:",
	];

	// 底部操作栏
	if (layoutInfo.bottomBar) {
		const bar = layoutInfo.bottomBar;
		hints.push(
			`- 底部操作栏: Figma 确认存在(name="${bar.name}", y=${bar.y}, h=${bar.height}),文字: [${(bar.texts || []).join(", ") || "无文字"}]。请在截图中验证是否可见。`,
		);
	} else {
		hints.push("- 底部操作栏: Figma 结构数据中**未检测到**固定底部操作栏。请仔细确认截图底部是否真的有按钮区域,如果没有则 bottomFixedBar.present 必须为 false。");
	}

	// 页面尺寸
	if (layoutInfo.rootSize) {
		hints.push(`- 页面尺寸: ${layoutInfo.rootSize.width} x ${layoutInfo.rootSize.height}`);
	}

	// 垂直分区
	if (layoutInfo.sections?.length > 0) {
		const sectionNames = layoutInfo.sections.map((s) => `${s.name}(y=${s.y})`).join(", ");
		hints.push(`- 页面垂直分区(从上到下): ${sectionNames}`);
	}

	// 重复模式
	if (layoutInfo.patterns?.length > 0) {
		for (const p of layoutInfo.patterns) {
			hints.push(`- 检测到 ${p.type}: ${p.count} 项, 每项 ${p.itemWidth}x${p.itemHeight}, 间距 ${p.gap}px`);
		}
	}

	return hints.join("\n");
}

function renderVisualSummaryMarkdown(summary) {
	if (!summary) {
		return "";
	}

	const lines = [
		"# Screenshot Visual Summary",
		"",
		`- pageType: ${summary.pageType || "desktop"}`,
		`- layoutOrder: ${summary.layoutOrder.join(" -> ") || "none"}`,
		`- filterGroupLabels: ${summary.filterGroupLabels.join(", ") || "none"}`,
		`- requiredSelectCount: ${summary.requiredSelectCount}`,
		`- headerTitle: ${summary.headerTitle || "none"}`,
		`- searchLabel: ${summary.searchLabel || "none"}`,
		`- primaryActionLabel: ${summary.primaryActionLabel || "none"}`,
		`- tableColumns: ${summary.tableColumns.join(", ") || "none"}`,
		`- actionColumnLabel: ${summary.actionColumnLabel || "none"}`,
		`- actionLinkLabel: ${summary.actionLinkLabel || "none"}`,
		`- pagination.present: ${String(summary.pagination.present)}`,
		`- pagination.containerAlignment: ${summary.pagination.containerAlignment || "none"}`,
		`- pagination.totalTextVisible: ${String(summary.pagination.totalTextVisible)}`,
		`- pagination.pageSizeSelectorVisible: ${String(summary.pagination.pageSizeSelectorVisible)}`,
		`- pagination.jumperVisible: ${String(summary.pagination.jumperVisible)}`,
		`- pagination.activePageStyle: ${summary.pagination.activePageStyle || "none"}`,
		`- style.backgroundTone: ${summary.style.backgroundTone || "none"}`,
		`- style.headerTone: ${summary.style.headerTone || "none"}`,
		`- style.primaryColor: ${summary.style.primaryColor || "none"}`,
	];

	// 移动端专用字段
	if (summary.pageType === "mobile") {
		if (summary.sectionOrder.length > 0) {
			lines.push(`- sectionOrder: ${summary.sectionOrder.join(" -> ")}`);
		}
		for (const section of summary.sections || []) {
			const conf = summary.sectionConfidence?.[section.name];
			const confStr = conf && conf !== "high" ? ` [confidence: ${conf}]` : "";
			lines.push(`- section[${section.name}]: ${section.description}${confStr}`);
			for (const overlay of section.floatingOverlays || []) {
				lines.push(`  - floatingOverlay: "${overlay.text}" @ ${overlay.position} — ${overlay.description}`);
			}
		}
		if (summary.bottomFixedBar?.present) {
			const secondary = Array.isArray(summary.bottomFixedBar.secondaryElements)
				? summary.bottomFixedBar.secondaryElements.filter(Boolean)
				: [];
			const secondaryStr = secondary.length > 0 ? `, secondary=[${secondary.map((s) => `"${s}"`).join(", ")}]` : "";
			const confidenceStr = summary.bottomFixedBar.confidence ? `, confidence=${summary.bottomFixedBar.confidence}` : "";
			const sourceStr = summary.bottomFixedBar.source ? `, source=${summary.bottomFixedBar.source}` : "";
			lines.push(
				`- bottomFixedBar: present, primaryButton="${summary.bottomFixedBar.primaryButtonText || "none"}"${secondaryStr}${confidenceStr}${sourceStr}`,
			);
		}
		for (const layout of summary.listLayouts || []) {
			const dirStr = layout.direction ? `, direction=${layout.direction}` : "";
			const labelStr = layout.labelOnTop !== undefined ? `, labelOnTop=${String(layout.labelOnTop)}` : "";
			lines.push(`- listLayout[${layout.section}]: ${layout.columns}col${dirStr}${labelStr} — ${layout.description}`);
		}
		if (summary.imageLayout?.pattern) {
			lines.push(
				`- imageLayout: ${summary.imageLayout.pattern}, firstFullWidth=${String(summary.imageLayout.firstImageFullWidth)}, thumbCols=${summary.imageLayout.thumbnailColumns}`,
			);
		}
		if (summary.priceSection?.countdownPosition) {
			lines.push(`- priceSection.countdownPosition: ${summary.priceSection.countdownPosition}`);
		}
	}

	if (Array.isArray(summary.keyColors) && summary.keyColors.length > 0) {
		lines.push(`- keyColors: ${summary.keyColors.join(", ")}`);
	}

	if (summary.notes.length > 0) {
		lines.push("", "## Notes", ...summary.notes.map((item) => `- ${item}`));
	}

	// 交叉校验警告
	const warnings = summary.crossValidationWarnings || [];
	if (warnings.length > 0) {
		lines.push(
			"",
			"## Cross-Validation Warnings (Figma vs Screenshot)",
			"Figma 结构数据优先级高于截图摘要:",
			...warnings.map((w) => `- ${w}`),
		);
	}

	lines.push("");
	return lines.join("\n");
}

/**
 * 通过读取 PNG 文件头判断截图宽度,宽度 < 500px 视为移动端页面
 */
async function detectMobileScreenshot(screenshotFilePath) {
	try {
		const buf = fs.readFileSync(screenshotFilePath);
		// PNG 文件:宽度在字节 16-19(4 字节 big-endian)
		if (buf.length > 24 && buf[0] === 0x89 && buf[1] === 0x50) {
			const width = buf.readUInt32BE(16);
			return width < 500;
		}
	} catch {}
	return false;
}

/**
 * 移动端页面专用的视觉摘要 prompt — 关注空间布局、元素位置、对齐方式
 */
function buildMobileVisionPrompt() {
	return [
		"你是 Venus 的截图视觉摘要器(移动端模式)。",
		"请只基于页面截图,输出一个 JSON 对象,不要输出解释性前缀或 markdown。",
		"重点关注元素的精确空间位置和对齐关系。",
		"",
		"**重要:精确描述规则(违反会导致代码生成错误)**",
		"- **只报告截图中 100% 确认存在的元素**。宁可漏报也不要多报。",
		"- **禁止推断、联想、补充**。如果截图中某元素模糊或被截断,视为不存在。",
		"- **数量必须精确计数**:逐个元素数清楚,不要估计。数完后再核对一遍。",
		"- **按钮文字必须逐字抄录**:从截图中读取按钮上的文字,一个字都不能改。",
		"- **description 字段只描述视觉事实**:不要写\"可能包含\"、\"应该有\"、\"通常会有\"等推测性内容。只写\"看到X个Y元素,文字为Z\"。",
		"",
		"**bottomFixedBar 字段说明**:",
		"- present: 截图最底部(通常 60-80px)是否**清晰可见**一个固定操作栏(通常是白底、有按钮)。**只有截图中明确看到按钮区域才算 true**。如果截图底部没有按钮区域,必须设为 false。不要猜测或推断。",
		"- primaryButtonText: 主按钮的确切文字(必须是截图中能读到的文字,逐字抄录)。如果 present=false,此字段留空",
		"- secondaryElements: **极严格限制** — 只有截图中能**清晰看到第二个独立按钮且能读出其文字**才填入。**以下情况必须填空数组 []:**",
		"  - 只看到 1 个按钮",
		"  - 看到图标但没有文字(不算按钮)",
		"  - 不确定是否有第二个按钮",
		"  - 第二个按钮文字模糊不清",
		"",
		"JSON 字段要求:",
		"{",
		'  "pageType": "mobile",',
		'  "sectionOrder": ["string"],',
		'  "sections": [',
		"    {",
		'      "name": "string",',
		'      "description": "string",',
		'      "floatingOverlays": [',
		'        { "text": "string", "position": "left-top|right-top|center-top|left-bottom|right-bottom|left-center|right-center|center-bottom", "description": "string" }',
		"      ]",
		"    }",
		"  ],",
		'  "bottomFixedBar": {',
		'    "present": false,',
		'    "confidence": "high",',
		'    "primaryButtonText": "string",',
		'    "secondaryElements": []',
		"  },",
		'  "listLayouts": [',
		'    { "section": "string", "type": "string", "columns": 1, "labelOnTop": true, "direction": "row|column", "description": "string" }',
		"  ],",
		'  "imageLayout": {',
		'    "pattern": "string",',
		'    "firstImageFullWidth": true,',
		'    "thumbnailColumns": 1,',
		'    "description": "string"',
		"  },",
		'  "priceSection": {',
		'    "countdownPosition": "string",',
		'    "countdownDescription": "string"',
		"  },",
		'  "sectionConfidence": {',
		'    "header": "high",',
		'    "mainImage": "high",',
		'    "...": "medium|low"',
		"  },",
		'  "keyColors": ["string"],',
		'  "notes": ["string"]',
		"}",
		"",
		"**置信度(confidence)说明**:",
		"- `high`: 截图中清晰可见,100% 确认",
		"- `medium`: 截图中可见但细节不够清晰(如文字模糊、部分被遮挡)",
		"- `low`: 不太确定,可能是推断而非确认(请尽量避免输出 low,如果不确定就留空或不报告)",
		"- `bottomFixedBar.confidence`: 对底部操作栏是否存在的整体置信度",
		"- `sectionConfidence`: 对每个 section 描述的置信度,key 为 section name,value 为 high/medium/low",
		"",
		"**空间位置描述规则(极其重要)**:",
		"- **「上方」/「下方」** 指垂直流中的位置关系,即元素在另一个元素的上面或下面(CSS flex-column 流中的前后顺序)。",
		"- **「悬浮在...上」/「叠加在...上」** 指一个元素覆盖在另一个元素的视觉区域内(CSS position:absolute 关系),两者在视觉上重叠。",
		"- **绝对禁止混淆**:如果一个文字/按钮/标签是**覆盖在图片上**(与图片在视觉上重叠),必须说「悬浮在图片上」或「叠加在图片上」,禁止说「图片上方」。",
		"- **示例**:",
		"  - ✗ 错误:「图片上方有灰色横幅文字'有102位用户收藏了这台车'」(暗示文字在图片上方、垂直流中先于图片)",
		"  - ✓ 正确:「图片上悬浮有灰色横幅文字'有102位用户收藏了这台车'」(文字覆盖在图片区域内)",
		"  - ✗ 错误:「下方有'外观'和'内饰'标签按钮」(暗示按钮在图片下方)",
		"  - ✓ 正确:「图片底部悬浮有'外观'和'内饰'两个标签按钮」(按钮覆盖在图片底部区域内)",
		"",
		"**floatingOverlays 强制规则**:",
		"- 任何**悬浮/叠加**在其他内容之上的元素(文字、按钮、标签、图标等),**必须**放入该 section 的 `floatingOverlays` 数组,不能仅写在 description 中。",
		"- position 必须精确:left-top/right-top/center-top/left-bottom/right-bottom/left-center/right-center/center-bottom",
		"- 如果某个元素既悬浮又有具体文字,description 中简要提一句\"图片上有悬浮元素\",完整信息放入 floatingOverlays",
		"",
		"重要说明:",
		"- sections[].description 必须只描述视觉事实,格式为\"看到N个X,排列为Y\"。禁止写\"包含\"、\"带有\"等推测性词汇。如果数不清楚,写\"若干\"而不是编一个错误数字",
		"- sectionOrder 是强制约束,必须严格按照截图中的从上到下顺序排列",
		"- listLayouts.columns 表示每行显示几列(非常重要,直接影响 grid-template-columns)",
		"- listLayouts.labelOnTop 表示标签和值的上下顺序(true=标签在上值在下,false=值在上标签在下)",
		"- listLayouts.direction 为 row 表示子元素横向排列,column 表示纵向排列",
		"- imageLayout 描述图片区域的布局模式",
		"- priceSection 描述价格相关区域的布局(仅电商/拍卖类页面需要)",
	].join("\n");
}

/**
 * PC 端页面的视觉摘要 prompt
 */
function buildDesktopVisionPrompt() {
	return [
		"你是 Venus 的截图视觉摘要器。",
		"请只基于页面截图,输出一个 JSON 对象,不要输出解释性前缀或 markdown。",
		"重点关注页面的区块布局、关键文字、表单元素、表格结构等可提取信息。",
		"",
		"**重要:精确描述规则**",
		"- 只报告截图中**清晰可见且有明确文字标注**的元素",
		"- 如果不确定某个元素是否存在,**不要猜测或编造**,直接留空或设为空数组",
		"- 数组字段(formFields、tableColumns、filterGroupLabels 等):只填写截图中实际看到的内容,看不到就填空数组 []",
		"- 文字必须是截图中能读到的确切文字,不要推断或联想",
		"- **必须使用精确数字**:描述数量时用确切数字(如\"4列表格\"、\"3个筛选项\"),不要用\"多个\"、\"若干\"、\"几个\"等模糊词",
		"",
		"JSON 字段要求:",
		"{",
		'  "pageType": "desktop",',
		'  "layoutOrder": ["string"],',
		'  "pageCategory": "list|detail|form|dashboard|other",',
		'  "headerTitle": "string",',
		'  "searchLabel": "string",',
		'  "primaryActionLabel": "string",',
		'  "filterGroupLabels": ["string"],',
		'  "requiredSelectCount": 0,',
		'  "tableColumns": ["string"],',
		'  "actionColumnLabel": "string",',
		'  "actionLinkLabel": "string",',
		'  "formFields": ["string"],',
		'  "pagination": {',
		'    "present": true,',
		'    "containerAlignment": "split|left|right",',
		'    "totalTextVisible": true,',
		'    "pageSizeSelectorVisible": true,',
		'    "jumperVisible": true,',
		'    "activePageStyle": "blue-filled|blue-outline|plain"',
		"  },",
		'  "style": {',
		'    "backgroundTone": "white|gray|mixed",',
		'    "headerTone": "light-gray|white|mixed",',
		'    "primaryColor": "blue|green|red|mixed"',
		"  },",
		'  "keyColors": ["string"],',
		'  "notes": ["string"]',
		"}",
		"说明:",
		"- layoutOrder 描述页面主要区块的从上到下顺序,只填区块标识(如 header/filters/toolbar/table/pagination/footer 等)",
		"- pageCategory 判断页面类型:列表页、详情页、表单页、仪表盘或其他",
		"- 表单页填写 formFields,列表页填写 tableColumns,详情页填写 pageCategory=detail 并描述内容区域",
		"- 如果页面没有筛选区/表格/分页等区块,对应字段留空或设为空数组",
	].join("\n");
}

async function summarizeScreenshotWithVisionModel(screenshotFilePath, layoutInfo = null) {
	if (!screenshotFilePath || !fileExists(screenshotFilePath)) {
		return null;
	}

	const baseUrl = process.env.AI_DIRECT_OPENAI_BASE_URL || process.env.OPENAI_BASE_URL;
	const apiKey = process.env.AI_DIRECT_OPENAI_API_KEY || process.env.OPENAI_API_KEY;
	const visionModel =
		process.env.AI_DIRECT_VISION_MODEL ||
		process.env.AI_DIRECT_OPENAI_VISION_MODEL ||
		process.env.OPENAI_VISION_MODEL ||
		"qwen-vl-max";

	if (!baseUrl || !apiKey || !visionModel) {
		const missing = [];
		if (!baseUrl) missing.push("AI_DIRECT_OPENAI_BASE_URL 或 OPENAI_BASE_URL");
		if (!apiKey) missing.push("AI_DIRECT_OPENAI_API_KEY 或 OPENAI_API_KEY");
		_log(`[ai-direct-messages] ⚠ 跳过截图视觉摘要:缺少环境变量 ${missing.join("、")}`);
		_log(`[ai-direct-messages]   提示:配置这些环境变量后,vision model 会分析截图并生成布局摘要,大幅提升设计还原度`);
		return null;
	}

	const mimeType = resolveScreenshotMimeType(screenshotFilePath);
	const dataUrl = `data:${mimeType};base64,${fs.readFileSync(screenshotFilePath).toString("base64")}`;
	const endpoint = `${baseUrl.replace(/\/$/, "")}/chat/completions`;

	// 根据截图尺寸判断页面类型(移动端 vs PC端),使用不同的 prompt 模板
	const isMobilePage = await detectMobileScreenshot(screenshotFilePath);
	let visionPrompt = isMobilePage ? buildMobileVisionPrompt() : buildDesktopVisionPrompt();

	// 注入 Figma 先验知识,减少 Vision Model 幻觉
	const figmaHints = buildFigmaPriorHints(layoutInfo);
	if (figmaHints) {
		visionPrompt += figmaHints;
	}

	// 构建 user message 文本,包含 Figma 先验提示
	let userText = isMobilePage
		? "请把这张移动端 Figma 页面截图总结成用于前端还原的视觉要点,特别注意元素的精确位置和对齐方式。"
		: "请把这张 Figma 页面截图总结成用于前端还原的视觉要点。";
	if (figmaHints) {
		userText += "\n\n请注意上方提供的 Figma 结构数据先验信息,据此验证你的视觉判断。如果 Figma 数据显示某元素不存在,请勿臆造。";
	}

	const response = await fetch(endpoint, {
		method: "POST",
		headers: {
			"content-type": "application/json",
			authorization: `Bearer ${apiKey}`,
			connection: "close",
		},
		signal: AbortSignal.timeout(120_000),
		body: JSON.stringify({
			model: visionModel,
			temperature: 0.1,
			messages: [
				{
					role: "system",
					content: visionPrompt,
				},
				{
					role: "user",
					content: [
						{
							type: "text",
							text: userText,
						},
						{
							type: "image_url",
							image_url: {
								url: dataUrl,
							},
						},
					],
				},
			],
		}),
	});

	if (!response.ok) {
		const errorText = (await response.text()).trim();
		const errorPreview = errorText ? ` | ${errorText.slice(0, 600)}` : "";
		throw new Error(`截图视觉摘要请求失败: ${response.status} ${response.statusText}${errorPreview}`);
	}

	const payload = await response.json();
	return normalizeVisualSummary(extractJsonPayload(payload.choices?.[0]?.message?.content || ""));
}

function buildUserMessageContent({
	bundle,
	promptText,
	designContext,
	variableDefsText,
	screenshotFilePath,
	screenshotSummary,
	singlePageMode,
}) {
	const prompt = buildUserPrompt({ bundle, promptText, designContext, variableDefsText, singlePageMode });
	const sections = [prompt];

	if (screenshotFilePath && fileExists(screenshotFilePath)) {
		sections.push(
			[
				"# Screenshot Context",
				`- Screenshot file: ${path.basename(screenshotFilePath)}`,
				"- 该截图来自当前 Figma node 的渲染结果,只用于辅助校正分区、留白、字段宽度、表格层次和分页位置。",
				"- 如果截图分析与 Figma 原始 design context、显式文本节点或组件事实源冲突,以数据源为准,不要让截图覆盖文本事实。",
			].join("\n"),
		);
	}

	if (screenshotSummary) {
		const summaryHints = [
			"# Screenshot Visual Summary JSON",
			"- 以下摘要仅作视觉辅助,不得覆盖 Figma 原始文本、placeholder、列名、示例数据或组件 API 事实。",
			"- **layoutOrder / sectionOrder 是强制约束**:如果 layoutOrder 或 sectionOrder 字段存在,你必须严格按照该顺序组织页面区块,不得擅自调整顺序。",
			"- **颜色值必须忠实还原**:设计稿中指定的颜色值(如 rgba(255,255,255,1))必须原样使用,禁止用'合理推断'覆盖。",
			"- **白色文字意味着深色背景**:如果设计稿中某元素使用白色文字,说明其背景为深色或图片,必须保留设计稿的背景上下文。",
		];

		// 移动端页面的额外布局约束
		if (screenshotSummary.pageType === "mobile") {
			summaryHints.push(
				"- **floatingOverlays 位置是强制约束**:每个 floatingOverlay 的 position(如 left-top/right-top/center-top)必须严格对应到 CSS 的 position:absolute 定位,不得自行推断位置。",
				"- **listLayouts.columns 是强制约束**:如果指定了 columns=2,CSS 必须使用 grid-template-columns: repeat(2, 1fr) 或等效布局,不得使用其他列数。",
				"- **listLayouts.direction 是强制约束**:direction=row 表示子元素横向排列(flex-direction: row),direction=column 表示纵向排列。",
				"- **listLayouts.labelOnTop**:true 表示标签在上、值在下;false 表示值在上、标签在下。必须按此顺序排列子元素。",
				"- **imageLayout 是强制约束**:如果 firstImageFullWidth=true,第一张图片必须独占一行;thumbnailColumns 指定剩余图片的列数。",
				"- **bottomFixedBar**:如果 present=true 且 confidence 不为 \"low\",页面底部必须有 position:fixed 的操作栏。如果 present=false 或 confidence=\"low\",你必须检查 Figma design context 中是否存在固定底部的 FRAME/GROUP,**仅当 Figma 数据明确支持时才生成底部操作栏,不得臆造**。",
				"- **priceSection**:如果存在,描述价格相关区域的布局(仅电商/拍卖类页面需要)。",
			);
		}

		summaryHints.push(JSON.stringify(screenshotSummary, null, 2));

		// 注入交叉校验警告
		const warnings = screenshotSummary.crossValidationWarnings || [];
		if (warnings.length > 0) {
			summaryHints.push(
				"",
				"# Cross-Validation Warnings (Figma vs Screenshot)",
				"以下是不一致项,**Figma 结构数据优先级高于截图摘要**。请以 Figma design context 为最终裁决依据:",
				...warnings.map((w) => `- ${w}`),
			);
		}

		sections.push(summaryHints.join("\n"));
	}

	return sections.join("\n\n");
}

function buildRequestMarkdown({ bundle, messages }) {
	return [
		"# AI Direct Request",
		"",
		`- Project: \`${bundle.projectContext.projectName}\``,
		`- Framework: \`${bundle.rules.framework}\``,
		`- Preferred VUI: \`${bundle.rules.preferredVuiPackage || "none"}\``,
		`- Fallbacks: \`${(bundle.rules.fallbackPackages || []).join(", ") || "none"}\``,
		"",
		"## System Message",
		"",
		"```text",
		messages[0].content,
		"```",
		"",
		"## User Message",
		"",
		"```text",
		messages[1].content,
		"```",
		"",
	].join("\n");
}

async function run() {
	const args = parseCliArgs();
	const bundlePath = deriveBundlePath(args);

	_log("[ai-direct-messages] 准备 AI 直投消息...");
	_log(`  → bundle: ${bundlePath}`);
	_log(`  → appendMode: ${args.appendMode}`);

	ensureBundle(args, bundlePath);
	const bundle = readJson(bundlePath);
	const bundleDir = path.dirname(bundlePath);
	const promptPath = resolveArtifactPath(bundleDir, bundle.artifacts.promptFile);
	const designContextPath = resolveArtifactPath(bundleDir, bundle.artifacts.designContextFile);
	const variableDefsPath = resolveArtifactPath(bundleDir, bundle.artifacts.variableDefsFile);

	_log("  → 读取输入文件...");
	const promptText = fs.readFileSync(promptPath, "utf8");
	const designContext = fs.readFileSync(designContextPath, "utf8");
	const variableDefsText =
		variableDefsPath && fileExists(variableDefsPath) ? fs.readFileSync(variableDefsPath, "utf8") : "";
	const screenshotPath = resolveArtifactPath(bundleDir, bundle.artifacts.screenshotFile);
	const layoutInfoPath = resolveArtifactPath(bundleDir, bundle.artifacts.layoutInfoFile || "");
	let layoutInfo = null;
	if (layoutInfoPath && fileExists(layoutInfoPath)) {
		try {
			layoutInfo = readJson(layoutInfoPath);
			_log(`  → 已加载 Figma layout-info: ${layoutInfoPath}`);
		} catch (error) {
			_log(`  → 加载 layout-info 失败,继续: ${error.message}`);
		}
	}

	const baseName = path.basename(bundlePath, ".ai-direct-context-bundle.json");
	const messagesPath = path.join(bundleDir, `${baseName}.messages.json`);
	const requestPath = path.join(bundleDir, `${baseName}.request.md`);
	const screenshotSummaryPath = path.join(bundleDir, `${baseName}.screenshot-summary.md`);
	const screenshotSummaryJsonPath = path.join(bundleDir, `${baseName}.screenshot-summary.json`);
	let screenshotSummary = null;

	if (screenshotPath && fileExists(screenshotPath)) {
		if (args.skipScreenshotSummary) {
			_log("  → 跳过截图视觉摘要(--skip-screenshot-summary)");
		} else {
			_log("  → 生成截图视觉摘要(调用 AI 模型)...");
			if (layoutInfo) {
				_log("  → 已注入 Figma 先验知识到 Vision prompt");
			}
			try {
				screenshotSummary = await summarizeScreenshotWithVisionModel(screenshotPath, layoutInfo);
				if (screenshotSummary) {
					// 交叉校验:用 Figma 结构化数据校验截图摘要
					if (layoutInfo) {
						screenshotSummary = crossValidateWithFigma(screenshotSummary, layoutInfo);
						const warnings = screenshotSummary.crossValidationWarnings || [];
						if (warnings.length > 0) {
							_log(`  → ⚠ 交叉校验发现 ${warnings.length} 个不一致:`);
							for (const w of warnings) {
								_log(`    - ${w}`);
							}
						} else {
							_log("  → ✓ 交叉校验通过,截图摘要与 Figma 数据一致");
						}
					}
					_log("  → ✓ 截图摘要完成");
					fs.writeFileSync(screenshotSummaryJsonPath, `${JSON.stringify(screenshotSummary, null, 2)}\n`, "utf8");
					fs.writeFileSync(screenshotSummaryPath, renderVisualSummaryMarkdown(screenshotSummary), "utf8");
				}
			} catch (error) {
				_log(`[ai-direct-messages] warning: 截图视觉摘要生成失败,继续走文本上下文: ${error.message}`);
			}
		}
	} else {
		_log("  → 无截图,跳过视觉摘要");
	}

	// 判断单页面模式:显式传入 或 bundle 没有 _batchMode(非多 URL 批次)
	const singlePageMode = args.singlePageMode || !bundle.figma?._batchMode;
	if (singlePageMode) {
		_log("  → 单页面模式:将生成完整页面文件到 views/ 下");
	}

	// 追加模式:读取已有页面结构
	_log("  → 扫描已有页面结构...");
	const appendContext = args.appendMode && args.projectDir ? readExistingViewsStructure(args.projectDir) : "";
	if (appendContext) {
		_log("[ai-direct-messages] 已注入已有页面结构到 prompt");
	}

	_log("  → 构建 Messages...");

	const messages = [
		{
			role: "system",
			content: buildSystemPrompt(bundle, appendContext),
		},
		{
			role: "user",
			content: buildUserMessageContent({
				bundle,
				promptText,
				designContext,
				variableDefsText,
				screenshotFilePath: screenshotPath,
				screenshotSummary,
				singlePageMode,
			}),
		},
	];

	const payload = {
		meta: {
			generator: "scripts/ai-direct-messages.mjs",
			generatedAt: new Date().toISOString(),
			bundleFile: normalizePath(bundlePath),
		},
		messages,
	};

	fs.writeFileSync(messagesPath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
	fs.writeFileSync(requestPath, buildRequestMarkdown({ bundle, messages }), "utf8");

	_log("[ai-direct-messages] ✓ 完成");
	_log(`  → messages: ${messagesPath}`);
	_log(`  → request: ${requestPath}`);
}

run()
	.then(() => {
		process.exit(0);
	})
	.catch((error) => {
		_log("[ai-direct-messages] 执行失败:", error.message);
		process.exit(1);
	});