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

import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";

import { loadComponentManifest } from "../packages/ai/design-mapper/src/index.mjs";
import { readProjectContext, toJson as toPrettyJson } from "../packages/ai/project-intelligence/src/index.mjs";
import { buildDesignSpec } from "./ai-direct-spec.mjs";
import { mapTokensToTheme, scanProjectTheme } from "./ai-direct-theme.mjs";
import {
	extractLayoutInfo,
	fetchDesignContext,
	fetchNodeDetails,
	fetchScreenshot,
	fetchVariableDefs,
	isMcpAvailable,
	parseFigmaUrl,
} from "./mcp-bridge/figma-client.mjs";
import { requireWorkspaceRoot } from "./workspace-root.mjs";

const _filename = fileURLToPath(import.meta.url);
const _dirname = path.dirname(_filename);

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

const repoRoot = requireWorkspaceRoot();
const KNOWN_PROJECT_UI_PACKAGES = ["@vui/vue", "@vui/react", "@vui/uniapp", "@vui/mobile", "element-plus", "ant-design-vue", "antd", "vant", "@vant/weapp"];
const WORKSPACE_PACKAGE_ROOTS = {
	"@vui/vue": "packages/vui/vue",
	"@vui/react": "packages/vui/react",
	"@vui/uniapp": "packages/vui/uniapp",
	"@vui/mobile": "packages/vui/mobile",
};
const PLATFORM_UI_CONFIG_PATH = path.join(_dirname, "ai-direct-platform-ui.config.json");
let _platformUiConfigCache = null;

function readPlatformUiConfig() {
	if (_platformUiConfigCache) {
		return _platformUiConfigCache;
	}

	try {
		if (fileExists(PLATFORM_UI_CONFIG_PATH)) {
			_platformUiConfigCache = JSON.parse(fs.readFileSync(PLATFORM_UI_CONFIG_PATH, "utf8"));
			return _platformUiConfigCache;
		}
	} catch (error) {
		console.warn(`[ai-direct-context] ⚠ 读取平台配置文件失败: ${error.message}`);
	}

	_platformUiConfigCache = { platforms: {}, detectionRules: {} };
	return _platformUiConfigCache;
}

function detectPlatform(projectContext, allDependencies = {}) {
	const config = readPlatformUiConfig();
	const detectionRules = config.detectionRules || {};
	const projectRoot = projectContext.projectRoot || "";
	const rootLower = projectRoot.toLowerCase();

	// 按优先级检测:小程序 > 移动端 > PC
	for (const [platformName, rules] of Object.entries(detectionRules)) {
		if (rules.anyDependency && rules.anyDependency.some((dep) => Boolean(allDependencies[dep]))) {
			return platformName;
		}
		if (rules.anyPathSegment && rules.anyPathSegment.some((seg) => rootLower.includes(seg.toLowerCase()))) {
			return platformName;
		}
	}

	// 框架兜底映射
	const framework = projectContext.framework || "unknown";
	if (framework === "react") return "react";
	if (framework === "uniappX") return "miniprogram";
	return "pc";
}

function getPlatformUiRule(platform) {
	const config = readPlatformUiConfig();
	const platformConfig = config.platforms?.[platform];
	if (platformConfig) {
		return {
			preferredVuiPackage: platformConfig.preferredVuiPackage || "",
			fallbackPackages: platformConfig.fallbackPackages || [],
			cliTemplate: platformConfig.cliTemplate || "",
			cliUiOption: platformConfig.cliUiOption || "",
			componentHints: platformConfig.componentHints || [],
			label: platformConfig.label || platform,
		};
	}

	// 配置文件不存在时的硬编码兜底(向后兼容)
	const fallbackRules = {
		pc: { preferredVuiPackage: "@vui/vue", fallbackPackages: ["element-plus"], cliTemplate: "vue", cliUiOption: "element-plus" },
		react: { preferredVuiPackage: "@vui/react", fallbackPackages: ["antd"], cliTemplate: "react", cliUiOption: "antd" },
		miniprogram: { preferredVuiPackage: "@vui/uniapp", fallbackPackages: ["@vant/weapp"], cliTemplate: "", cliUiOption: "" },
		mobile: { preferredVuiPackage: "@vui/mobile", fallbackPackages: ["vant"], cliTemplate: "mobile", cliUiOption: "vant" },
		unknown: { preferredVuiPackage: "", fallbackPackages: [], cliTemplate: "", cliUiOption: "" },
	};

	const rule = fallbackRules[platform] || fallbackRules.unknown;
	return { ...rule, componentHints: [], label: platform };
}

function parseCliArgs() {
	const args = process.argv.slice(2);
	const parsed = {
		projectDir: "",
		figmaUrl: "",
		pageName: "",
		pageTitle: "",
		outputDir: "",
		withoutScreenshot: false,
		withoutVariables: false,
		targetPlatform: "",
		fallbackUi: "",
	};

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

		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 if (arg === "--without-screenshot") {
			parsed.withoutScreenshot = true;
		} else if (arg === "--without-variables") {
			parsed.withoutVariables = true;
		} else if (arg === "--target-platform" && next) {
			parsed.targetPlatform = next;
			index++;
		} else if (arg === "--fallback-ui" && next) {
			parsed.fallbackUi = next;
			index++;
		}
	}

	return parsed;
}

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

function ensureDir(targetDir) {
	fs.mkdirSync(targetDir, { recursive: true });
}

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

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

function screenshotExtensionForMimeType(mimeType) {
	switch (String(mimeType || "").toLowerCase()) {
		case "image/jpeg":
		case "image/jpg": {
			return ".jpg";
		}
		case "image/webp": {
			return ".webp";
		}
		default: {
			return ".png";
		}
	}
}

function toRelativeSchemaPath(fromDir, targetFile) {
	return normalizePath(path.relative(fromDir, targetFile));
}

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

	const title = pageTitle || derivePageTitle(figmaUrl);
	return toPascalCase(title);
}

function deriveOutputDir(projectDir, outputDir, pageSlug) {
	if (outputDir) {
		return path.isAbsolute(outputDir) ? outputDir : path.resolve(projectDir, outputDir);
	}

	return path.join(projectDir, ".ai-direct", pageSlug);
}

function normalizeFramework(projectContext, platformOverride) {
	const platform = platformOverride || detectPlatform(projectContext);
	if (platform === "react") return "react";
	if (platform === "miniprogram") return "uniappX";
	if (platform === "mobile" || platform === "pc") return "vue";
	const framework = projectContext.framework || "unknown";
	if (framework === "vue" || framework === "react" || framework === "uniappX") {
		return framework;
	}
	return "unknown";
}

function resolvePlatformAndRule(projectContext, allDependencies, cliOverrides) {
	// CLI override 优先
	const platform = cliOverrides.targetPlatform || detectPlatform(projectContext, allDependencies);
	const rule = getPlatformUiRule(platform);

	// 如果用户指定了 --fallback-ui,替换 fallbackPackages
	if (cliOverrides.fallbackUi) {
		rule.fallbackPackages = [cliOverrides.fallbackUi];
	}

	return { platform, rule };
}

function getFrameworkUiRule(projectContext, allDependencies, cliOverrides) {
	return resolvePlatformAndRule(projectContext, allDependencies, cliOverrides || {}).rule;
}

function resolveManifestPathByPackage(packageName) {
	const manifestByPackage = {
		"@vui/vue": path.join(repoRoot, "packages/vui/vue/meta/index.json"),
		"@vui/mobile": path.join(repoRoot, "packages/vui/mobile/meta/index.json"),
		"element-plus": path.join(repoRoot, "contracts/ai/element-plus.manifest.json"),
		antd: path.join(repoRoot, "contracts/ai/antd.manifest.json"),
		"ant-design-vue": path.join(repoRoot, "contracts/ai/ant-design-vue.manifest.json"),
	};

	const candidate = manifestByPackage[packageName];
	if (!candidate || !fileExists(candidate)) {
		return "";
	}

	return candidate;
}

function buildEmptyCatalog(packageName, framework, reason) {
	return {
		packageName,
		framework,
		notes: reason,
		projectInstalled: false,
		components: [],
	};
}

function extractDependencies(projectDir) {
	const packageJsonPath = path.join(projectDir, "package.json");
	const packageJson = readJson(packageJsonPath);
	return {
		packageJson,
		allDependencies: {
			...packageJson.dependencies,
			...packageJson.devDependencies,
		},
	};
}

function detectProjectUiPackages(allDependencies) {
	return KNOWN_PROJECT_UI_PACKAGES.filter((pkg) => Boolean(allDependencies[pkg]));
}

function resolveWorkspacePackageRoot(packageName) {
	const relativeRoot = WORKSPACE_PACKAGE_ROOTS[packageName];
	if (!relativeRoot) {
		return "";
	}

	const absoluteRoot = path.join(repoRoot, relativeRoot);
	return fileExists(absoluteRoot) ? absoluteRoot : "";
}

function collectExportsFromSource(sourceText) {
	const exportNames = new Set();
	const matches = sourceText.matchAll(/export\s+\{\s*(?:default\s+as\s+)?(\w+)\s*\}\s+from/g);

	for (const match of matches) {
		exportNames.add(match[1]);
	}

	return [...exportNames];
}

function readWorkspacePackageExports(packageName) {
	const packageRoot = resolveWorkspacePackageRoot(packageName);
	if (!packageRoot) {
		return null;
	}

	const packageJsonPath = path.join(packageRoot, "package.json");
	const packageJson = readJson(packageJsonPath);
	const sourceFiles = [
		path.join(packageRoot, "src", "index.ts"),
		path.join(packageRoot, "src", "components", "index.ts"),
	].filter((filePath) => fileExists(filePath));

	const exportNames = new Set();
	for (const filePath of sourceFiles) {
		const sourceText = fs.readFileSync(filePath, "utf8");
		for (const exportName of collectExportsFromSource(sourceText)) {
			exportNames.add(exportName);
		}
	}

	return {
		packageName,
		packageRoot: normalizePath(path.relative(repoRoot, packageRoot)),
		exportNames: [...exportNames].sort(),
		version: packageJson.version || "0.0.0",
	};
}

function summarizeComponent(component, manifestPackageName, projectUiPackages) {
	return {
		exportName: component.exportName,
		category: component.category || "",
		description: component.description || "",
		source: component.source || "",
		semanticRoles: component.semanticRoles || [],
		supportedKinds: component.supportedKinds || [],
		supportedActionKinds: component.supportedActionKinds || [],
		supportedFieldTypes: component.supportedFieldTypes || [],
		supportedScopes: component.supportedScopes || [],
		props: (component.props || []).map((prop) => ({
			name: prop.name,
			type: prop.type || "",
			description: prop.description || "",
		})),
		events: (component.events || []).map((event) => ({
			name: event.name,
			payload: event.payload || "",
			description: event.description || "",
		})),
		slots: (component.slots || []).map((slot) => ({
			name: slot.name,
			description: slot.description || "",
		})),
		usageGuidance: component.usageGuidance || {},
		figmaMapping: component.figmaMapping || {},
		packageInstalledInProject: projectUiPackages.includes(manifestPackageName),
	};
}

function buildManifestCatalog(manifest, projectUiPackages) {
	return {
		packageName: manifest.packageName,
		framework: manifest.framework,
		notes: manifest.notes || "",
		projectInstalled: projectUiPackages.includes(manifest.packageName),
		components: (manifest.components || []).map((component) =>
			summarizeComponent(component, manifest.packageName, projectUiPackages),
		),
	};
}

function buildSelectionRules({ projectContext, projectUiPackages, workspaceExports, allDependencies, cliOverrides }) {
	const resolved = resolvePlatformAndRule(projectContext, allDependencies || {}, cliOverrides || {});
	const uiRule = resolved.rule;
	const platform = resolved.platform;
	const framework = normalizeFramework(projectContext, platform);
	const preferredVuiPackage = uiRule.preferredVuiPackage;
	const fallbackPackages = uiRule.fallbackPackages;
	const preferredPackageExports =
		workspaceExports.find((pkg) => pkg.packageName === preferredVuiPackage)?.exportNames || [];
	const installedPreferredPackage = preferredVuiPackage && projectUiPackages.includes(preferredVuiPackage);

	const componentSelection = [];

	if (preferredVuiPackage) {
		// 有首选 VUI 层(如 PC 端 @vui/vue、移动端 @vui/mobile)
		componentSelection.push(
			"优先复用项目当前已安装且已导出的 UI 组件,不要为了贴近设计稿随意引入一个项目里没有的组件包。",
			`当前平台 (${platform}) 的首选 VUI 包为 \`${preferredVuiPackage}\`,必须把它作为第一顺位组件体系。`,
			"生成代码时必须基于组件 manifest 的 props、events、slots 和 usageGuidance,而不是凭印象猜组件。",
			installedPreferredPackage
				? `项目已安装 \`${preferredVuiPackage}\`,AI 必须优先使用该包的组件;只有确认不覆盖目标场景时才允许降级。`
				: `项目当前未安装 \`${preferredVuiPackage}\`。若要使用 VUI,AI 必须显式提出依赖补齐;若本次不调整依赖,再按框架规则降级。`,

		);

		if (preferredPackageExports.length > 0) {
			componentSelection.push(
				`${preferredVuiPackage} 当前可见导出组件: ${preferredPackageExports.join(", ")}。不得写出超出当前可见导出的组件 import。`,
			);
		}

		if (fallbackPackages.length > 0) {
			componentSelection.push(
				`如果 ${preferredVuiPackage} 无法覆盖当前设计场景,按框架降级到: ${fallbackPackages.join(", ")}。降级组件只作为第二顺位,不能默认优先使用。`,
			);
		}

		// 移动端专属提示:禁止混用 PC 端组件
		if (platform === "mobile") {
			componentSelection.push(
				"⚠ 移动端场景禁止使用 @vui/vue 的 VInput/VSelect/VTable/VButton/VDialog 等 PC 端组件。PC 端组件不能用于移动端 H5。",
			);
		}
	} else {
		// 当前平台没有首选 VUI 层(如移动端 @vui/mobile 尚未建设)
		componentSelection.push(
			`当前平台 (${platform}) 没有首选 VUI 组件包(@vui/mobile 尚未建设),直接以降级组件库作为唯一组件来源。`,
			"优先复用项目当前已安装且已导出的 UI 组件,不要为了贴近设计稿随意引入一个项目里没有的组件包。",
			"生成代码时必须基于组件 manifest 的 props、events、slots 和 usageGuidance,而不是凭印象猜组件。",
		);

		if (platform === "mobile") {
			componentSelection.push(
				"⚠ 禁止使用 @vui/vue 的 VInput、VSelect、VTable、VButton、VDialog 等 PC 端组件,它们是 PC 管理后台专用的,不能用于移动端 H5。",
				"移动端必须使用 Vant 4 的组件实现(van-field、van-picker、van-button、van-cell、van-list、van-nav-picker 等)。",
			);
		} else if (platform === "miniprogram" && fallbackPackages.length > 0) {
			componentSelection.push(
				`⚠ 禁止使用 @vui/vue 的 PC 端组件。小程序端使用降级组件库: ${fallbackPackages.join(", ")}。`,
			);
		}

		if (fallbackPackages.length > 0) {
			componentSelection.push(
				`当前平台使用降级组件库: ${fallbackPackages.join(", ")},这是默认且唯一的组件来源。`,
			);
		}
	}

	if (uiRule.componentHints && uiRule.componentHints.length > 0) {
		componentSelection.push(`当前平台组件使用提示:\n${uiRule.componentHints.map((h) => `- ${h}`).join("\n")}`);
	}

	return {
		platform,
		framework,
		preferredVuiPackage,
		fallbackPackages,
		enforcement: {
			mustUseVuiFirst: Boolean(preferredVuiPackage),
			allowedFallbacks: fallbackPackages,
		},
		previewProjectPolicy: {
			mustUseVenusCli: true,
			cliTemplate: uiRule.cliTemplate,
			cliUiOption: uiRule.cliUiOption,
		},
		componentSelection,
		generationConstraints: [
			"页面生成由 AI 直接完成,Venus 不再负责中间映射裁决。",
			"生成结果必须尽量保持设计结构,但优先保证组件选型与项目现有依赖一致。",
			"页面级视觉和布局必须在本次生成产物内一并完成,不得依赖人工再到预览产物里补样式。",
			"若设计稿表达与现有组件能力冲突,应先保证结构和交互合理,再在说明中标记差异点。",
			"如果某个设计元素无法稳定映射到现有组件,优先退回基础容器和简单 DOM,而不是选择一个语义错误的复杂组件。",
			"生成预览项目时必须使用 Venus CLI 创建项目骨架,不得手工新建一套独立脚手架。",
			"不得假设预览项目壳层会额外提供业务页所需的头图、渐变背景、导航或布局补丁,页面应自带完整容器、间距、尺寸和必要样式。",
		],
		validationGoals: [
			"通过 lint、typecheck、template contract、review trigger 和 fitness 等根级质量门禁。",
			"不得引入项目中不存在的组件 import。",
			"不得绕过项目现有路由、目录和命名约定。",
			"必须优先满足 VUI 第一顺位与按框架降级的规则。",
			"预览项目必须基于 Venus CLI 生成的项目结构。",
			"预览页面不能依赖模板演示壳层样式才能成立,生成文件本身应包含可运行的页面结构与样式。",
		],
	};
}

function buildAiPrompt({
	projectContext,
	projectUiPackages,
	pageName,
	pageTitle,
	figmaUrl,
	bundleFileName,
	designContextFileName,
	variableDefsFileName,
	screenshotFileName,
	designSpec,
	themeMapping,
	layoutInfo,
	workspaceExports,
	selectionRules,
}) {
	const framework = normalizeFramework(projectContext, selectionRules.platform);
	const preferredVui = selectionRules.preferredVuiPackage || "VUI";
	const fallbacks = selectionRules.fallbackPackages;
	const previewTemplate = selectionRules.previewProjectPolicy.cliTemplate;
	const previewUiOption = selectionRules.previewProjectPolicy.cliUiOption;
	const previewCommand =
		previewTemplate && previewUiOption
			? `pnpm venus create ${slugify(pageName)}-preview --template ${previewTemplate} --router --store --ui ${previewUiOption} --eslint --no-install`
			: "";
	const lines = [
		"# AI Direct Generation Context",
		"",
		"## Task",
		"",
		`- Generate a page for \`${projectContext.projectName}\` (framework: \`${framework}\`).`,
		`- Page name: \`${pageName}\``,
		`- Page title: \`${pageTitle}\``,
		`- Figma URL: ${figmaUrl}`,
		"",
		"## Required Inputs",
		"",
		`- Read \`${bundleFileName}\` first for project constraints and component facts.`,
		`- Read \`${designContextFileName}\` as the raw Figma developer MCP context.`,
	];

	if (variableDefsFileName) {
		lines.push(`- Read \`${variableDefsFileName}\` for design token and variable hints.`);
	}
	if (screenshotFileName) {
		lines.push(`- Read \`${screenshotFileName}\` as the rendered screenshot context of the selected Figma node.`);
	}

	lines.push(
		"",
		"## Project UI Packages",
		"",
		`- Installed UI packages: ${projectUiPackages.join(", ") || "none detected"}`,
		"",
		"## Package Exports",
		"",
	);

	for (const packageExport of workspaceExports) {
		lines.push(
			`- ${packageExport.packageName}: ${packageExport.exportNames.join(", ") || "no source exports detected"}`,
		);
	}

	lines.push(
		"",
		"## Generation Rules",
		"",
		`- VUI is mandatory first choice: prefer \`${preferredVui}\` before any fallback UI library.`,
		`- Framework fallback chain: ${fallbacks.length > 0 ? fallbacks.join(" -> ") : "none"}.`,
		"- Do not import components from packages that are not installed in the target project unless you explicitly plan a dependency change.",
		"- When a design element cannot be mapped confidently, keep structure simple and explain the gap instead of forcing a wrong component.",
		"- Keep output aligned with the target project's routing, naming, and directory conventions.",
		"- Preview project scaffolding must use Venus CLI. Do not handcraft a new scaffold.",
		...(previewCommand ? [`- Recommended preview command: \`${previewCommand}\`.`] : []),
	);

	// 注入 Design Spec (token candidates + patterns + uncertainty)
	if (designSpec) {
		lines.push(
			"",
			"## Design Spec (从 Figma 提取的结构化设计信号)",
			"",
			"以下 token candidates 是从设计稿中提取的设计信号,**不是最终变量名**,必须映射到项目的语义主题变量后使用。",
			"",
		);

		// Token candidates
		if (designSpec.tokens?.colors?.length > 0) {
			lines.push("### Color Tokens");
			for (const token of designSpec.tokens.colors.slice(0, 15)) {
				lines.push(`- \`${token.value}\` (推断角色: ${token.role})`);
			}
			lines.push("");
		}
		if (designSpec.tokens?.spacing?.length > 0) {
			lines.push("### Spacing Tokens");
			lines.push(`- ${designSpec.tokens.spacing.map((t) => `\`${t.value}\``).join(", ")}`, "");
		}
		if (designSpec.tokens?.typography?.length > 0) {
			lines.push("### Typography Tokens");
			lines.push(`- ${designSpec.tokens.typography.map((t) => `\`${t.fontSize || t.lineHeight}\``).join(", ")}`, "");
		}

		// Patterns
		if (designSpec.patterns?.length > 0) {
			lines.push("### UI Patterns");
			for (const pattern of designSpec.patterns) {
				lines.push(`- **${pattern.type}**: ${pattern.description}`);
			}
			lines.push("");
		}

		// Uncertainty
		if (designSpec.uncertainty?.length > 0) {
			lines.push("### Uncertainty (设计稿中未明确的决策点)");
			for (const item of designSpec.uncertainty) {
				lines.push(`- **${item.type}**: ${item.description} — ${item.impact}`);
			}
			lines.push("");
		}
	}

	// 注入 Theme Mapping (token → 语义变量映射)
	if (themeMapping) {
		lines.push(
			"",
			"## Theme Mapping (设计信号 → 语义变量)",
			"",
			"**必须使用以下语义变量,禁止直接写硬编码颜色/间距值。**",
			"",
		);

		// Color mapping
		const reusedColors = themeMapping.colors?.filter((c) => c.status === "reused" || c.status === "approximate") || [];
		if (reusedColors.length > 0) {
			lines.push("### 颜色映射 (复用已有变量)");
			for (const mapping of reusedColors) {
				lines.push(`- \`${mapping.designValue}\` → \`${mapping.semanticVariable}\` (${mapping.recommendation})`);
			}
			lines.push("");
		}

		const missingColors = themeMapping.colors?.filter((c) => c.status === "missing") || [];
		if (missingColors.length > 0) {
			lines.push("### 颜色映射 (缺失,建议新增)");
			for (const mapping of missingColors) {
				lines.push(`- \`${mapping.designValue}\` (角色: ${mapping.inferredRole}) — ${mapping.recommendation}`);
			}
			lines.push("");
		}

		// Spacing mapping
		const reusedSpacing = themeMapping.spacing?.filter((s) => s.status === "reused" || s.status === "approximate") || [];
		if (reusedSpacing.length > 0) {
			lines.push("### 间距映射");
			for (const mapping of reusedSpacing) {
				lines.push(`- \`${mapping.designValue}\` → \`${mapping.semanticVariable}\``);
			}
			lines.push("");
		}

		lines.push(
			"### 生成规则",
			"",
			"- **禁止**直接写 `color: rgba(...)` 或 `background: #xxx`,必须使用 `var(--vui-color-*)` 或 `var(--background)` 等语义变量",
			"- **禁止**直接写 `padding: 16px`,优先使用 Tailwind 的 `p-4` 或 CSS 变量 `var(--spacing-4)`",
			"- 如果语义变量表中没有匹配项,优先使用最接近的已有变量,而非硬编码",
			"- 所有颜色值必须通过 semantic role 消费,保证全局主题一致性",
			"",
		);
	}

	// 注入 Layout Info (Figma 语义化布局摘要)
	if (layoutInfo && (layoutInfo.sections?.length > 0 || layoutInfo.textNodes?.length > 0)) {
		lines.push(
			"",
			"## Figma Layout Info (精确坐标与布局数据)",
			"",
		);
		if (layoutInfo.rootName) {
			lines.push(`页面名称: ${layoutInfo.rootName}`);
		}
		if (layoutInfo.rootSize) {
			lines.push(`页面尺寸: ${layoutInfo.rootSize.width} x ${layoutInfo.rootSize.height}`);
		}
		lines.push("");

		// 垂直分区
		if (layoutInfo.sections?.length > 0) {
			lines.push("### 页面垂直分区(从上到下)", "");
			for (const s of layoutInfo.sections) {
				const parts = [`y=${s.y}, ${s.width}x${s.height}`];
				if (s.cssFlex) {
					const f = s.cssFlex;
					parts.push(`CSS: display:${f.display}; flex-direction:${f.flexDirection}; gap:${f.gap}; justify-content:${f.justifyContent}; align-items:${f.alignItems}`);
				} else if (s.layout) {
					parts.push(`layout: ${s.layout}${s.gap ? `, gap: ${s.gap}px` : ""}`);
				}
				if (s.texts?.length > 0) {
					parts.push(`文本: ${s.texts.join(", ")}`);
				}
				if (s.componentName) {
					parts.push(`组件: ${s.componentName}`);
				}
				lines.push(`- **${s.name}** (${s.type}): ${parts.join(" | ")}`);
			}
			lines.push("");
		}

		// 底部固定栏
		if (layoutInfo.bottomBar) {
			const bar = layoutInfo.bottomBar;
			const textsStr = bar.texts?.length > 0 ? ` | 按钮: ${bar.texts.join(", ")}` : "";
			lines.push(`### 底部固定栏`, `- y=${bar.y}, ${bar.width}x${bar.height}${textsStr}`, `- **必须生成 position:fixed; bottom:0 的操作栏**`, "");
		}

		// 检测到的布局模式
		if (layoutInfo.patterns?.length > 0) {
			lines.push("### 检测到的重复布局模式", "");
			for (const p of layoutInfo.patterns) {
				if (p.type === "vertical-list") {
					lines.push(`- **垂直列表**: ${p.count}项, 每项${p.itemWidth}x${p.itemHeight}, 间距${p.gap}px`);
					if (p.sampleTexts?.length > 0) {
						lines.push(`  示例: ${p.sampleTexts.join(", ")}`);
					}
				} else if (p.type === "horizontal-row") {
					lines.push(`- **水平行**: ${p.count}项, 每项${p.itemWidth}x${p.itemHeight}, 间距${p.gap}px`);
					if (p.sampleTexts?.length > 0) {
						lines.push(`  示例: ${p.sampleTexts.join(", ")}`);
					}
				}
			}
			lines.push("");
		}

		// 关键文本节点(带坐标)
		if (layoutInfo.textNodes?.length > 0) {
			lines.push("### 关键文本节点坐标", "", "| 文本 | 位置(x,y) | 尺寸(w×h) | 字号 |", "|------|-----------|-----------|------|");
			for (const t of layoutInfo.textNodes) {
				lines.push(`| ${t.text} | (${t.x},${t.y}) | ${t.w}×${t.h} | ${t.fontSize || "-"} |`);
			}
			lines.push("");
		}

		lines.push(
			"### 布局解读指南",
			"",
			"- 当分区显示 `CSS: display:flex; ...` 时,直接使用对应的 CSS Flexbox 属性还原布局",
			"- `justify-content` 映射自 Figma primaryAxisAlignItems(MIN→flex-start, CENTER→center, MAX→flex-end, SPACE_BETWEEN→space-between)",
			"- `align-items` 映射自 Figma counterAxisAlignItems(MIN→flex-start, CENTER→center, MAX→flex-end, BASELINE→baseline)",
			"- 当分区显示 `组件: xxx` 时,该节点是 Figma Component Instance,名称可用于推断应映射到哪个 VUI 组件",
			"- 文本节点坐标可帮助你精确定位元素在页面中的位置",
			"- **垂直列表**模式 → 用 `v-for` + flex column 生成",
			"- **水平行**模式 → 用 flex row + gap 生成",
			"- **底部固定栏** → 仅当 Figma layout-info 中 bottomBar 不为 null 时才生成,必须用 `position:fixed; bottom:0; left:0; right:0`",
			"",
		);
	}

	lines.push(
		"",
		"## Expected Output",
		"",
		"- A directly usable Vue page implementation.",
		"- A brief note listing any dependency gaps or component capability gaps that block closer restoration.",
		"",
	);

	return `${lines.join("\n")}\n`;
}

function buildBundle({
	schemaReference,
	figmaUrl,
	projectContext,
	projectUiPackages,
	pageName,
	pageTitle,
	pageSlug,
	designContext,
	variableDefsFile,
	screenshotFile,
	screenshotSummaryFile,
	designSpecFile,
	themeMappingFile,
	layoutInfoFile,
	designContextFile,
	promptFile,
	workspaceExports,
	selectionRules,
	vuiCatalog,
	fallbackCatalogs,
}) {
	const { fileKey, nodeId } = parseFigmaUrl(figmaUrl);

	return {
		$schema: schemaReference,
		meta: {
			generator: "scripts/ai-direct-context.mjs",
			mode: "ai-direct",
			generatedAt: new Date().toISOString(),
			repoRoot: normalizePath(repoRoot),
		},
		figma: {
			figmaUrl,
			fileKey: fileKey || "",
			nodeId: nodeId || "",
			pageName,
			pageTitle,
			pageSlug,
			designContextExcerpt: designContext.slice(0, 2400),
		},
		projectContext,
		projectUi: {
			projectInstalledPackages: projectUiPackages,
			workspacePackageExports: workspaceExports,
		},
		componentFacts: {
			preferredPackages: selectionRules.preferredVuiPackage ? [selectionRules.preferredVuiPackage] : [],
			fallbackPackages: selectionRules.fallbackPackages,
			vuiCatalog,
			fallbackCatalogs,
		},
		rules: selectionRules,
		artifacts: {
			designContextFile: normalizePath(designContextFile),
			variableDefsFile: variableDefsFile ? normalizePath(variableDefsFile) : "",
			screenshotFile: screenshotFile ? normalizePath(screenshotFile) : "",
			screenshotSummaryFile: screenshotSummaryFile ? normalizePath(screenshotSummaryFile) : "",
			designSpecFile: normalizePath(designSpecFile),
			themeMappingFile: normalizePath(themeMappingFile),
			layoutInfoFile: layoutInfoFile ? normalizePath(layoutInfoFile) : "",
			promptFile: normalizePath(promptFile),
		},
	};
}

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

	if (!args.projectDir || !args.figmaUrl) {
		console.error(
			'用法: node scripts/ai-direct-context.mjs --project-dir ./apps/web/demo --figma-url "https://www.figma.com/design/..."',
		);
		process.exit(1);
	}

	const projectDir = path.resolve(args.projectDir);
	if (!fileExists(projectDir)) {
		console.error(`错误: 项目目录不存在: ${projectDir}`);
		process.exit(1);
	}

	_log("[ai-direct-context] Venus AI 直生上下文打包器");
	_log(`  → 项目目录: ${projectDir}`);
	_log(`  → Figma URL: ${args.figmaUrl}`);

	_log("\n[step 0] 检查 figma-developer-mcp...");
	const mcpAvailable = await isMcpAvailable();
	if (!mcpAvailable) {
		console.error("  ✗ figma-developer-mcp 不可达,无法准备 AI 直生上下文。");
		process.exit(1);
	}
	_log("  ✓ figma-developer-mcp 可用");

	const pageTitle = args.pageTitle || derivePageTitle(args.figmaUrl);
	const pageName = derivePageName(args.pageName, pageTitle, args.figmaUrl);
	const pageSlug = slugify(pageName);
	const outputDir = deriveOutputDir(projectDir, args.outputDir, pageSlug);
	ensureDir(outputDir);

	_log("\n[step 1] 拉取 Figma 设计上下文...");
	const designContext = await fetchDesignContext(args.figmaUrl);
	_log(`  ✓ design context: ${designContext.length} 字符`);

	let screenshot = null;
	if (!args.withoutScreenshot) {
		_log("\n[step 2] 拉取 Figma 截图上下文...");
		try {
			screenshot = await fetchScreenshot(args.figmaUrl);
			_log(`  ✓ screenshot fetched (${screenshot.mimeType || "image/png"})`);
		} catch (error) {
			console.warn(`  ⚠ 截图获取失败,继续生成上下文包: ${error.message}`);
		}
	}

	let variableDefs = null;
	if (!args.withoutVariables) {
		_log("\n[step 3] 拉取 Figma 变量定义...");
		try {
			variableDefs = await fetchVariableDefs(args.figmaUrl);
			_log("  ✓ variable definitions fetched");
		} catch (error) {
			console.warn(`  ⚠ 变量定义获取失败,继续生成上下文包: ${error.message}`);
		}
	}

	let layoutInfo = null;
	_log("\n[step 3.5] 拉取 Figma 节点布局详情(坐标/AutoLayout)...");
	try {
		const nodeDetails = await fetchNodeDetails(args.figmaUrl);
		layoutInfo = extractLayoutInfo(nodeDetails);
		_log(`  ✓ layout info: ${layoutInfo.totalNodes} 节点, ${layoutInfo.autoLayoutCount} AutoLayout, ${layoutInfo.fixedPositionCount} 约束定位`);
	} catch (error) {
		console.warn(`  ⚠ 节点布局详情获取失败,继续生成上下文包: ${error.message}`);
	}

	_log("\n[step 4] 读取项目上下文与组件事实源...");
	const projectContext = readProjectContext(projectDir);
	const { allDependencies } = extractDependencies(projectDir);
	const projectUiPackages = detectProjectUiPackages(allDependencies);
	const cliOverrides = { targetPlatform: args.targetPlatform, fallbackUi: args.fallbackUi };
	const selectionRules = buildSelectionRules({ projectContext, projectUiPackages, workspaceExports: [], allDependencies, cliOverrides });
	const workspaceExports = [
		readWorkspacePackageExports("@vui/vue"),
		readWorkspacePackageExports("@vui/react"),
		readWorkspacePackageExports("@vui/uniapp"),
		readWorkspacePackageExports("@vui/mobile"),
	].filter(Boolean);
	const finalizedSelectionRules = buildSelectionRules({ projectContext, projectUiPackages, workspaceExports, allDependencies, cliOverrides });

	const preferredManifestPath = resolveManifestPathByPackage(finalizedSelectionRules.preferredVuiPackage);
	const preferredManifest = preferredManifestPath ? loadComponentManifest(preferredManifestPath) : null;
	const vuiCatalog = preferredManifest
		? buildManifestCatalog(preferredManifest, projectUiPackages)
		: buildEmptyCatalog(
			finalizedSelectionRules.preferredVuiPackage || "unknown",
			normalizeFramework(projectContext, finalizedSelectionRules.platform),
			"当前框架的 VUI manifest 尚未提供,AI 仍需遵守 VUI 第一顺位规则。",
		);
	const fallbackCatalogs = finalizedSelectionRules.fallbackPackages.map((pkg) => {
		const manifestPath = resolveManifestPathByPackage(pkg);
		const manifest = manifestPath ? loadComponentManifest(manifestPath) : null;
		return manifest
			? buildManifestCatalog(manifest, projectUiPackages)
			: buildEmptyCatalog(pkg, normalizeFramework(projectContext, finalizedSelectionRules.platform), "当前降级包 manifest 尚未提供。");
	});

	_log(`  → 平台: ${finalizedSelectionRules.platform}`);
	_log(`  → 项目 UI 包: ${projectUiPackages.join(", ") || "none"}`);
	_log(`  → Preferred VUI: ${finalizedSelectionRules.preferredVuiPackage || "none"}`);
	_log(`  → Fallback: ${finalizedSelectionRules.fallbackPackages.join(", ") || "none"}`);
	_log(`  → Preferred VUI components: ${vuiCatalog.components.length}`);
	_log(
		`  → Fallback catalogs: ${fallbackCatalogs.map((catalog) => `${catalog.packageName}=${catalog.components.length}`).join(", ") || "none"}`,
	);

	_log("\n[step 4.5] 构建 Design Spec + Theme Mapping...");
	let designSpec = null;
	let projectTheme = null;
	let themeMapping = null;
	try {
		designSpec = buildDesignSpec(designContext);
		projectTheme = scanProjectTheme(repoRoot);
		themeMapping = designSpec ? mapTokensToTheme(designSpec, projectTheme) : null;
		if (designSpec) {
			_log(`  → spec: ${designSpec.tokens?.colors?.length || 0} colors, ${designSpec.tokens?.spacing?.length || 0} spacing, ${designSpec.patterns?.length || 0} patterns`);
		} else {
			_log("  ⚠ design spec 为空(design context 可能格式不匹配)");
		}
		if (projectTheme) {
			_log(`  → theme: ${Object.keys(projectTheme.colors).length} color vars, ${Object.keys(projectTheme.spacing).length} spacing vars`);
		}
		if (themeMapping) {
			_log(`  → mapping: ${themeMapping.colors?.filter((c) => c.status === "reused").length || 0} reused, ${themeMapping.colors?.filter((c) => c.status === "missing").length || 0} missing`);
		}
	} catch (error) {
		_log(`  ⚠ Design Spec/Theme Mapping 构建失败,跳过: ${error.message}`);
	}

	_log("\n[step 5] 写入上下文包...");
	const designContextFile = path.join(outputDir, `${pageSlug}.design-context.html`);
	const variableDefsFile = variableDefs ? path.join(outputDir, `${pageSlug}.variable-defs.json`) : "";
	const screenshotFile = screenshot
		? path.join(outputDir, `${pageSlug}.screenshot${screenshotExtensionForMimeType(screenshot.mimeType)}`)
		: "";
	const screenshotSummaryFile = screenshot ? path.join(outputDir, `${pageSlug}.screenshot-summary.json`) : "";
	const designSpecFile = path.join(outputDir, `${pageSlug}.design-spec.json`);
	const themeMappingFile = path.join(outputDir, `${pageSlug}.theme-mapping.json`);
	const layoutInfoFile = layoutInfo ? path.join(outputDir, `${pageSlug}.layout-info.json`) : "";
	const promptFile = path.join(outputDir, `${pageSlug}.prompt.md`);
	const bundleFile = path.join(outputDir, `${pageSlug}.ai-direct-context-bundle.json`);

	const promptContent = buildAiPrompt({
		projectContext,
		projectUiPackages,
		pageName,
		pageTitle,
		figmaUrl: args.figmaUrl,
		bundleFileName: path.basename(bundleFile),
		designContextFileName: path.basename(designContextFile),
		variableDefsFileName: variableDefsFile ? path.basename(variableDefsFile) : "",
		screenshotFileName: screenshotFile ? path.basename(screenshotFile) : "",
		designSpec,
		themeMapping,
		layoutInfo,
		workspaceExports,
		selectionRules: finalizedSelectionRules,
	});

	const bundle = buildBundle({
		schemaReference: toRelativeSchemaPath(
			outputDir,
			path.join(repoRoot, "contracts/ai/ai-direct-context-bundle.schema.json"),
		),
		figmaUrl: args.figmaUrl,
		projectContext,
		projectUiPackages,
		pageName,
		pageTitle,
		pageSlug,
		designContext,
		variableDefsFile,
		screenshotFile,
		screenshotSummaryFile,
		designSpecFile,
		themeMappingFile,
		layoutInfoFile,
		designContextFile,
		promptFile,
		workspaceExports,
		selectionRules: finalizedSelectionRules,
		vuiCatalog,
		fallbackCatalogs,
	});

	fs.writeFileSync(designContextFile, designContext, "utf8");
	if (variableDefsFile) {
		fs.writeFileSync(variableDefsFile, toPrettyJson(variableDefs), "utf8");
	}
	if (screenshotFile && screenshot?.base64) {
		fs.writeFileSync(screenshotFile, Buffer.from(screenshot.base64, "base64"));
	}
	fs.writeFileSync(designSpecFile, toPrettyJson(designSpec), "utf8");
	fs.writeFileSync(themeMappingFile, toPrettyJson(themeMapping), "utf8");
	if (layoutInfoFile && layoutInfo) {
		fs.writeFileSync(layoutInfoFile, toPrettyJson(layoutInfo), "utf8");
	}
	fs.writeFileSync(promptFile, promptContent, "utf8");
	fs.writeFileSync(bundleFile, toPrettyJson(bundle), "utf8");

	_log("\n[ai-direct-context] ✓ 完成");
	_log(`  → bundle: ${bundleFile}`);
	_log(`  → prompt: ${promptFile}`);
	_log(`  → design context: ${designContextFile}`);
	_log(`  → design spec: ${designSpecFile}`);
	_log(`  → theme mapping: ${themeMappingFile}`);
	if (layoutInfoFile) {
		_log(`  → layout info: ${layoutInfoFile}`);
	}
	if (variableDefsFile) {
		_log(`  → variable defs: ${variableDefsFile}`);
	}
	if (screenshotFile) {
		_log(`  → screenshot: ${screenshotFile}`);
	}
	process.exit(0);
}

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