ai-direct-apply-output.mjs 29.3 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
#!/usr/bin/env node
import childProcess from "node:child_process";
import fs from "node:fs";
import path from "node:path";

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 */ }
	}
};
const _warn = (...args) => {
	const msg = `${_tp()} ${args.map(String).join(" ")}`;
	if (process.stderr.isTTY) {
		process.stderr.write(`${msg}\n`);
	} else {
		try { fs.writeSync(2, `${msg}\n`); } catch { /* noop */ }
	}
};

function parseCliArgs() {
	const args = process.argv.slice(2);
	const parsed = {
		responseFile: "",
		previewFile: "",
		model: "",
		provider: "",
		appendMode: false,
		pageName: "",
		batchUrls: [],
		singlePageMode: false,
	};

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

		if (arg === "--response-file" && next) {
			parsed.responseFile = next;
			index++;
		} else if (arg === "--preview-file" && next) {
			parsed.previewFile = next;
			index++;
		} else if (arg === "--model" && next) {
			parsed.model = next;
			index++;
		} else if (arg === "--provider" && next) {
			parsed.provider = next;
			index++;
		} else if (arg === "--append-mode") {
			parsed.appendMode = true;
		} else if (arg === "--single-page-mode") {
			parsed.singlePageMode = true;
		} else if (arg === "--page-name" && next) {
			parsed.pageName = next;
			index++;
		} else if (arg === "--batch-urls" && next) {
			parsed.batchUrls = next.split(",").map((u) => u.trim()).filter(Boolean);
			index++;
		} else if (arg === "--batch-index" && next) {
			parsed.batchIndex = Number.parseInt(next, 10);
			index++;
		} else if (arg === "--component-names" && next) {
			try {
				parsed.componentNames = JSON.parse(next);
			} catch {
				parsed.componentNames = {};
			}
			index++;
		} else if (arg === "--register-routes-only") {
			parsed.registerRoutesOnly = true;
		} else if (arg === "--project-root" && next) {
			parsed.projectRoot = next;
			index++;
		}
	}

	return parsed;
}

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

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

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

function runCommand(command, args, cwd) {
	const result = childProcess.spawnSync(command, args, {
		cwd,
		shell: process.platform === "win32",
		encoding: "utf8",
	});

	return {
		command: `${command} ${args.join(" ")}`.trim(),
		cwd: normalizePath(cwd),
		exitCode: result.status ?? 1,
		stdout: result.stdout || "",
		stderr: result.stderr || "",
		ok: (result.status ?? 1) === 0,
	};
}

function buildCoAuthorHeader(model, provider) {
	const timestamp = new Date().toISOString();
	const tool = "venus-ai-direct";
	const modelPart = model || "unknown-model";
	const providerPart = provider || "unknown-provider";
	const text = `@ai-co-author ${tool} | ${providerPart}/${modelPart} | ${timestamp}`;
	return { text, line: `// ${text}` };
}

function prependCoAuthorHeader(filePath, headerLine) {
	const existing = fs.readFileSync(filePath, "utf8");
	if (existing.includes("@ai-co-author")) {
		return;
	}
	fs.writeFileSync(filePath, `${headerLine}\n${existing}`, "utf8");
}

function writeAttributionManifest(projectRoot, attributionEntries, model, provider) {
	const manifestPath = path.join(projectRoot, ".ai-attribution.json");

	// 合并已有记录,避免后续批次覆盖前面的文件
	let existingFiles = [];
	if (fs.existsSync(manifestPath)) {
		try {
			const existing = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
			if (Array.isArray(existing.files)) {
				existingFiles = existing.files;
			}
		} catch { /* ignore */ }
	}

	// 按 path 去重,新的覆盖旧的
	const fileMap = new Map();
	for (const entry of existingFiles) {
		fileMap.set(entry.path, entry);
	}
	for (const entry of attributionEntries) {
		fileMap.set(entry.path, entry);
	}

	const manifest = {
		generator: "scripts/ai-direct-apply-output.mjs",
		generatedAt: new Date().toISOString(),
		model: model || "unknown",
		provider: provider || "unknown",
		files: [...fileMap.values()],
	};
	fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
	return manifestPath;
}

function generateModuleParentComponent(projectRoot, moduleFiles) {
	if (moduleFiles.length === 0) return null;

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

	// 找出所有模块组件(排除 index.vue 和 App.vue)
	const modules = moduleFiles
		.filter((f) => f.path.startsWith("src/views/") && f.path.endsWith(".vue"))
		.filter((f) => !f.path.endsWith("/index.vue") && !f.path.endsWith("/App.vue"))
		.map((f) => {
			const relativePath = f.path.replace(/^src\/views\//, "");
			const componentName = path.basename(relativePath, ".vue");
			return {
				path: f.path,
				relativePath,
				componentName,
				importName: toPascalCase(componentName),
			};
		});

	if (modules.length === 0) return null;

	// 生成父组件代码
	const imports = modules.map((m) => `import ${m.importName} from './${m.relativePath}';`).join("\n");
	const templateParts = modules.map((m) => `    <${m.importName} />`).join("\n");

	const parentComponent = `<script setup lang="ts">
${imports}
</script>

<template>
  <div class="page-container">
${templateParts}
  </div>
</template>

<style scoped>
.page-container {
  width: 100%;
  height: 100%;
}
</style>
`;

	const parentPath = path.join(viewsDir, "index.vue");
	fs.writeFileSync(parentPath, parentComponent, "utf8");

	return {
		path: "src/views/index.vue",
		moduleCount: modules.length,
		modules: modules.map((m) => m.componentName),
	};
}

function toPascalCase(str) {
	return str
		.split(/[-_\s]+/)
		.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
		.join("");
}

function runAutoFix(writtenFiles) {
	if (writtenFiles.length === 0) {
		return [];
	}

	const prettierTargetFiles = writtenFiles.map((file) => file.path);
	const eslintTargetFiles = prettierTargetFiles.filter((file) => /\.(?:cjs|cts|js|jsx|mjs|mts|ts|tsx|vue)$/.test(file));
	const stylelintTargetFiles = prettierTargetFiles.filter((file) => /\.(?:css|scss|vue)$/.test(file));
	const results = [
		runCommand("pnpm", ["exec", "prettier", "--write", "--ignore-unknown", ...prettierTargetFiles], repoRoot),
	];

	if (eslintTargetFiles.length > 0) {
		results.push(runCommand("pnpm", ["exec", "eslint", "--fix", ...eslintTargetFiles], repoRoot));
	}

	if (stylelintTargetFiles.length > 0) {
		results.push(runCommand("pnpm", ["exec", "stylelint", "--fix", ...stylelintTargetFiles], repoRoot));
	}

	return results;
}

function validateResponseShape(response) {
	// 为所有字段提供默认值,而不是抛出错误
	if (!response.summary) {
		response.summary = "AI generated code";
	}
	if (!response.dependencyPlan) {
		response.dependencyPlan = { needsDependencyChange: false, packages: [], reason: "No dependencies needed" };
	}
	if (!response.previewProject) {
		response.previewProject = { mustUseVenusCli: false, recommendedCommand: "" };
	}
	if (!response.notes) {
		response.notes = [];
	}
	if (!response.validationChecklist) {
		response.validationChecklist = [];
	}

	if (!Array.isArray(response.files) || response.files.length === 0) {
		_warn("[ai-direct-apply-output] ⚠ AI 输出 files 为空数组或缺失,跳过本次写入");
		response.files = [];
	}

	for (const file of response.files) {
		for (const key of ["path", "language", "purpose", "content"]) {
			if (!(key in file)) {
				throw new Error(`AI 输出 file 缺少字段: ${key}`);
			}
		}
	}
}

function toKebabCase(value) {
	return String(value || "")
		.replaceAll(/([a-z0-9])([A-Z])/g, "$1-$2")
		.replaceAll(/[^a-z0-9]+/gi, "-")
		.replaceAll(/^-+|-+$/g, "")
		.toLowerCase();
}

function collectVueViews(srcDir) {
	const viewsDir = path.join(srcDir, "views");
	if (!fs.existsSync(viewsDir)) return [];

	const views = [];
	const seenNames = new Set();
	const entries = fs.readdirSync(viewsDir, { withFileTypes: true });

	for (const entry of entries) {
		if (entry.isFile() && entry.name.endsWith(".vue")) {
			const baseName = entry.name.replace(/\.vue$/, "");
			if (baseName === "NotFound" || baseName === "App") continue;
			if (seenNames.has(baseName)) continue;
			seenNames.add(baseName);
			views.push({
				name: baseName,
				componentPath: `@/views/${entry.name}`,
				viewPath: `views/${entry.name}`,
			});
		}
	}

	for (const entry of entries) {
		if (entry.isDirectory()) {
			const indexFile = path.join(viewsDir, entry.name, "index.vue");
			if (!fs.existsSync(indexFile)) continue;
			if (seenNames.has(entry.name)) continue;
			seenNames.add(entry.name);
			views.push({
				name: entry.name,
				componentPath: `@/views/${entry.name}/index.vue`,
				viewPath: `views/${entry.name}/index.vue`,
			});
		}
	}

	return views;
}

// 自动为有 components/ 目录但缺少 index.vue 的页面目录生成组合页
function ensurePageIndexForPageDirs(projectRoot) {
	const viewsDir = path.join(projectRoot, "src", "views");
	if (!fs.existsSync(viewsDir)) return [];

	const created = [];
	const entries = fs.readdirSync(viewsDir, { withFileTypes: true });

	for (const entry of entries) {
		if (!entry.isDirectory()) continue;
		const pageDir = path.join(viewsDir, entry.name);
		const componentsDir = path.join(pageDir, "components");
		const indexPath = path.join(pageDir, "index.vue");

		// 只处理有 components/ 目录但缺少 index.vue 的页面
		if (!fs.existsSync(componentsDir)) continue;
		if (fs.existsSync(indexPath)) continue;

		// 扫描 components/ 下的 .vue 文件
		const componentFiles = fs.readdirSync(componentsDir)
			.filter((f) => f.endsWith(".vue"))
			.map((f) => f.replace(/\.vue$/, ""));

		if (componentFiles.length === 0) continue;

		// 生成 index.vue,引入并组合所有子组件
		const pageName = entry.name;
		const pageClass = `${pageName}-page`;
		const imports = componentFiles
			.map((name) => `import ${toPascalCase(name)} from "./components/${name}.vue";`)
			.join("\n");
		const templateParts = componentFiles
			.map((name) => `    <${toPascalCase(name)} />`)
			.join("\n");

		const content = `<script setup lang="ts">
${imports}
</script>

<template>
  <div class="${pageClass}">
${templateParts}
  </div>
</template>

<style scoped>
.${pageClass} {
  display: flex;
  flex-direction: column;
}
</style>
`;
		fs.writeFileSync(indexPath, content, "utf8");
		_log(`[ensurePageIndexForPageDirs] ✓ 自动生成 ${entry.name}/index.vue(包含 ${componentFiles.length} 个组件)`);
		created.push(entry.name);
	}

	return created;
}

function registerRoutesInRouter(projectRoot) {
	const routerCandidates = [
		path.join(projectRoot, "src", "router", "index.ts"),
		path.join(projectRoot, "src", "router.ts"),
	];
	let routerFile = "";
	for (const candidate of routerCandidates) {
		if (fs.existsSync(candidate)) {
			routerFile = candidate;
			break;
		}
	}
	if (!routerFile) return { count: 0, routerFile: "" };

	const srcDir = path.join(projectRoot, "src");
	const views = collectVueViews(srcDir);
	if (views.length === 0) {
		const cleanedUp = cleanupStaleRoutes(routerFile, projectRoot);
		return { count: 0, routerFile, staleRoutesRemoved: cleanedUp };
	}

	let routerContent = fs.readFileSync(routerFile, "utf8");

	// 移除指向 App.vue 的占位路由(如 { path: "/", component: () => import("../App.vue") })
	routerContent = routerContent.replaceAll(
		/\{[^}]*component:\s*\(\)\s*=>\s*import\(["']\.\.\/App\.vue["']\)[^}]*\},?\s*/g,
		"",
	);

	const registeredComponents = new Set();
	const importRegex = /import\(["']@\/views\/([^"']+)["']\)/g;
	let match;
	while ((match = importRegex.exec(routerContent)) !== null) {
		registeredComponents.add(`views/${match[1]}`);
	}

	const newViews = views.filter((v) => !registeredComponents.has(v.viewPath));
	if (newViews.length === 0) {
		// 没有新路由要注册,但仍需清理失效路由
		const cleanedUp = cleanupStaleRoutes(routerFile, projectRoot);
		return { count: 0, routerFile, staleRoutesRemoved: cleanedUp };
	}

	const routeEntries = newViews.map((v) => {
		const routePath = v.name === "Home" ? "/" : `/${toKebabCase(v.name)}`;
		return `\t{\n\t\tpath: "${routePath}",\n\t\tname: "${v.name}",\n\t\tcomponent: () => import("${v.componentPath}"),\n\t\tmeta: {\n\t\t\ttitle: "${v.name}",\n\t\t},\n\t},`;
	});

	const notFoundMarker = "path: \"/:pathMatch(.*)*\"";
	const markerIndex = routerContent.indexOf(notFoundMarker);
	if (markerIndex === -1) {
		// 没有 NotFound 路由,直接插入到数组末尾 ] 之前
		const arrayEnd = routerContent.lastIndexOf("];");
		if (arrayEnd === -1) return { count: 0, routerFile };
		const before = routerContent.slice(0, arrayEnd);
		const separator = before.trimEnd().endsWith(",") ? "" : ",";
		routerContent = `${before}${separator}\n${routeEntries.join("\n")}\n${routerContent.slice(arrayEnd)}`;
	} else {
		// 有 NotFound 路由,插入到它之前
		const routeStart = routerContent.lastIndexOf("{", markerIndex);
		if (routeStart === -1) return { count: 0, routerFile };
		// 往前找到行首,确保正确缩进
		const lineStart = routerContent.lastIndexOf("\n", routeStart) + 1;
		const before = routerContent.slice(0, lineStart);
		const separator = before.trimEnd().endsWith(",") ? "" : ",";
		routerContent = `${before}${separator}\n${routeEntries.join("\n")}\n${routerContent.slice(lineStart)}`;
	}

	fs.writeFileSync(routerFile, routerContent, "utf8");

	// 清理指向不存在文件的路由(处理前批次残留目录被清理后的脏路由)
	const cleanedUp = cleanupStaleRoutes(routerFile, projectRoot);

	return { count: newViews.length, routerFile, staleRoutesRemoved: cleanedUp };
}

// 移除路由文件中指向不存在文件的路由条目
function cleanupStaleRoutes(routerFile, projectRoot) {
	let content = fs.readFileSync(routerFile, "utf8");
	const srcDir = path.join(projectRoot, "src");
	let removed = 0;

	// 匹配所有 import("...") 路径,检查文件是否存在
	const routeImportPattern = /import\(["']((?:@\/views\/|\.\.\/views\/)[^"']+)["']\)/g;
	let routeMatch;
	const stalePaths = [];

	while ((routeMatch = routeImportPattern.exec(content)) !== null) {
		const importPath = routeMatch[1];
		// 将 @/views/xxx 或 ../views/xxx 解析为实际文件路径
		const relativePart = importPath.replace(/^@\/views\//, "").replace(/^\.\.\/views\//, "");
		const filePath = path.join(srcDir, "views", relativePart);
		if (!fs.existsSync(filePath)) {
			stalePaths.push(importPath);
		}
	}

	for (const stalePath of stalePaths) {
		// 匹配包含这个 import 的整个路由对象 { ... }
		const escapedPath = stalePath.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
		// 匹配从 { 到 }, 的路由块,包含该 import 路径
		const routeBlockPattern = new RegExp(
			`\\{[^{}]*?import\\(["']${escapedPath}["']\\)[^{}]*?\\},?\\s*`,
			"g",
		);
		const before = content;
		content = content.replaceAll(routeBlockPattern, "");
		if (content !== before) {
			removed++;
		}
	}

	if (removed > 0) {
		fs.writeFileSync(routerFile, content, "utf8");
		_log(`[cleanupStaleRoutes] ✓ 移除 ${removed} 条失效路由(指向不存在的文件)`);
	}

	return removed;
}

// 立即更新 index.vue:添加组件 import 和使用
function appendComponentToIndex(pageDir, componentName) {
	const indexPath = path.join(pageDir, "index.vue");
	const pageName = path.basename(pageDir);
	const pageClass = `${pageName}-page`;

	// 读取现有 index.vue 或创建新的
	let content = "";
	if (fs.existsSync(indexPath)) {
		content = fs.readFileSync(indexPath, "utf8");
	} else {
		// 创建空的 index.vue
		content = `<script setup lang="ts">
</script>

<template>
  <div class="${pageClass}">
  </div>
</template>

<style scoped>
.${pageClass} {
  display: flex;
  flex-direction: column;
}
</style>
`;
	}

	const importStatement = `import ${componentName} from "./components/${componentName}.vue";`;
	const componentUsage = `    <${componentName} />`;

	// 检查是否已存在
	if (content.includes(importStatement)) {
		return; // 已存在,跳过
	}

	// 添加 import 到 <script setup> 的末尾
	const scriptEndTag = "</script>";
	const scriptEndIndex = content.indexOf(scriptEndTag);
	if (scriptEndIndex === -1) {
		_log(`[appendComponentToIndex] 警告: 未找到 </script> 标签`);
		return;
	}

	const beforeScript = content.slice(0, scriptEndIndex);
	const afterScript = content.slice(scriptEndIndex);
	content = `${beforeScript}${importStatement}\n${afterScript}`;

	// 添加组件使用到 <template> 的末尾 </div> 之前
	const templateEndTag = "</div>";
	const templateEndIndex = content.lastIndexOf(templateEndTag);
	if (templateEndIndex === -1) {
		_log(`[appendComponentToIndex] 警告: 未找到 </div> 标签`);
		return;
	}

	const beforeTemplate = content.slice(0, templateEndIndex);
	const afterTemplate = content.slice(templateEndIndex);
	content = `${beforeTemplate}${componentUsage}\n${afterTemplate}`;

	fs.writeFileSync(indexPath, content, "utf8");
	_log(`[appendComponentToIndex] ✓ 已添加 ${componentName} 到 index.vue`);
}

function resolveTargetPath(projectRoot, relativeFilePath) {
	if (path.isAbsolute(relativeFilePath)) {
		throw new Error(`不允许写入绝对路径: ${relativeFilePath}`);
	}

	const normalized = relativeFilePath.replaceAll("\\", "/");
	if (normalized.includes("../")) {
		throw new Error(`不允许越出项目目录: ${relativeFilePath}`);
	}

	return path.resolve(projectRoot, normalized);
}

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

	// 仅注册路由模式
	if (args.registerRoutesOnly) {
		if (!args.projectRoot) {
			throw new Error("--register-routes-only 模式需要提供 --project-root");
		}
		console.log(`[ai-direct-apply-output] 仅注册路由模式: ${args.projectRoot}`);
		ensurePageIndexForPageDirs(args.projectRoot);
		const routerResult = registerRoutesInRouter(args.projectRoot);
		if (routerResult.count > 0) {
			console.log(`[ai-direct-apply-output] ✓ 自动注册路由: ${routerResult.count} 个新页面`);
		} else {
			console.log("[ai-direct-apply-output] 没有需要注册的新路由");
		}
		return;
	}

	if (!args.responseFile || !args.previewFile) {
		throw new Error("用法: node scripts/ai-direct-apply-output.mjs --response-file <ai-output.json> --preview-file <preview-project.json>");
	}

	const responsePath = path.resolve(args.responseFile);
	const previewPath = path.resolve(args.previewFile);

	// 读取 response 文件并检查内容
	const rawResponse = fs.readFileSync(responsePath, "utf8");
	console.log(`[ai-direct-apply-output] Response file size: ${rawResponse.length} characters`);
	if (rawResponse.length < 100) {
		console.error(`[ai-direct-apply-output] ⚠ AI 返回内容过短,可能是错误或拒绝:`);
		console.error(`  ${rawResponse.slice(0, 200)}`);
	}

	let response;
	try {
		response = JSON.parse(rawResponse);
	} catch (error) {
		console.error(`[ai-direct-apply-output] ✗ AI 返回的不是有效 JSON:`);
		console.error(`  ${rawResponse.slice(0, 500)}`);
		throw new Error(`AI 返回内容无法解析为 JSON: ${error.message}`);
	}

	const preview = readJson(previewPath);
	validateResponseShape(response);

	const projectRoot = preview.previewProject?.projectRoot;
	if (!projectRoot) {
		throw new Error("preview-project 缺少 projectRoot");
	}

	console.log("[ai-direct-apply-output] 应用 AI 结构化结果...");
	console.log(`  → response: ${responsePath}`);
	console.log(`  → project: ${projectRoot}`);
	console.log(`  → model: ${args.model || "unknown"}`);
	console.log(`  → provider: ${args.provider || "unknown"}`);

	// AI 贡献追踪:构建 co-author 头部注释
	const coAuthorHeader = buildCoAuthorHeader(args.model, args.provider);
	const attributionEntries = [];

	// 路由文件由模板生成,AI 不应覆盖;registerRoutesInRouter 会自动追加路由
	const routerFilePatterns = new Set(["src/router.ts", "src/router/index.ts"]);
	const skippedRouterFiles = [];
	const writtenFiles = [];

	// 单页面模式(追加模式 + 单 URL):写入 views/{pageName}/index.vue,遵循页面目录规范
	if (args.appendMode && args.singlePageMode) {
		const viewsDir = path.join(projectRoot, "src", "views");
		const pageDir = path.join(viewsDir, args.pageName || "FigmaPage");
		ensureDir(pageDir);

		for (const file of response.files || []) {
			const normalized = (file.path || "").replaceAll("\\", "/");
			if (routerFilePatterns.has(normalized)) {
				skippedRouterFiles.push(normalized);
				continue;
			}
			if (!normalized.endsWith(".vue") && !normalized.endsWith(".ts")) continue;

			// 强制规范化路径:确保页面入口写到 views/{pageName}/index.vue
			let targetPath;
			if (normalized.endsWith(".vue")) {
				// 检查 AI 是否正确生成了 views/{pageName}/index.vue
				const expectedPattern = `views/${args.pageName}/index.vue`;
				const flatPattern = `views/${args.pageName}.vue`;
				if (normalized.endsWith(expectedPattern) || normalized.endsWith("/index.vue")) {
					// AI 遵循了规范,直接使用
					targetPath = path.join(projectRoot, normalized);
				} else if (normalized.endsWith(flatPattern)) {
					// AI 生成了旧格式 views/{pageName}.vue,纠正为 views/{pageName}/index.vue
					targetPath = path.join(pageDir, "index.vue");
				} else {
					// 其他路径(如 AI 生成了其他组件),按原路径写入
					targetPath = path.join(projectRoot, normalized);
				}
			} else {
				// .ts 文件(tools/ 等),按原路径写入
				targetPath = path.join(projectRoot, normalized);
			}

			ensureDir(path.dirname(targetPath));
			fs.writeFileSync(targetPath, file.content, "utf8");
			prependCoAuthorHeader(targetPath, coAuthorHeader.line);

			const relativePath = normalizePath(path.relative(repoRoot, targetPath));
			writtenFiles.push({
				path: relativePath,
				language: file.language,
				purpose: file.purpose,
			});
			attributionEntries.push({
				path: relativePath,
				language: file.language,
				purpose: file.purpose,
				coAuthor: coAuthorHeader.text,
				action: "created",
			});
		}

		if (skippedRouterFiles.length > 0) {
			console.log(`[ai-direct-apply-output] 跳过路由文件: ${skippedRouterFiles.join(", ")}`);
		}
		console.log(`[ai-direct-apply-output] ✓ 单页面模式: ${writtenFiles.length} 个文件写入 ${pageDir}`);
	}
	// 多批次模式:管道控制文件组织,忽略 AI 的路径
	else if (args.appendMode && args.pageName && args.batchUrls.length > 0) {
		const viewsDir = path.join(projectRoot, "src", "views");
		const componentsDir = path.join(viewsDir, args.pageName, "components");
		ensureDir(componentsDir);

		let fileIndex = 0;

		for (const file of response.files || []) {
			const normalized = (file.path || "").replaceAll("\\", "/");
			if (routerFilePatterns.has(normalized)) {
				skippedRouterFiles.push(normalized);
				continue;
			}

			// 只处理 .vue 文件,忽略其他
			if (!normalized.endsWith(".vue")) continue;

			// 管道决定文件名:优先使用用户自定义名称,其次使用 AI 返回的文件名,最后兜底
			const batchUrl = fileIndex < args.batchUrls.length ? args.batchUrls[fileIndex] : null;
			let componentName;

			if (batchUrl && args.componentNames && args.componentNames[batchUrl]) {
				// 1. 用户通过 --component-names 显式指定
				componentName = args.componentNames[batchUrl];
			} else if (normalized) {
				// 2. 使用 AI 返回的 files[].path 中的文件名(AI 根据内容归纳的语义化名称)
				const aiBasename = path.basename(normalized, ".vue");
				const meaninglessPattern = /^(?:Node\d+|Frame\s*\d+|Group\s*\d+|FigmaPage|index|Component\d+_\d+)$/i;
				if (aiBasename && !meaninglessPattern.test(aiBasename)) {
					componentName = toPascalCase(aiBasename);
				}
			}

			if (!componentName) {
				// 3. 兜底:从 Figma URL 提取节点 ID
				if (batchUrl) {
					const nodeMatch = batchUrl.match(/node-id=([^&]+)/);
					if (nodeMatch) {
						const nodeId = nodeMatch[1].replaceAll(":", "").replaceAll("-", "");
						componentName = `Node${nodeId}`;
					}
				}
				componentName = componentName || `Component${args.batchIndex || 0}_${fileIndex}`;
			}

			const fileName = `${componentName}.vue`;
			const targetPath = path.join(componentsDir, fileName);

			fs.writeFileSync(targetPath, file.content, "utf8");
			prependCoAuthorHeader(targetPath, coAuthorHeader.line);

			const relativePath = normalizePath(path.relative(repoRoot, targetPath));
			writtenFiles.push({
				path: relativePath,
				language: file.language,
				purpose: file.purpose,
			});
			attributionEntries.push({
				path: relativePath,
				language: file.language,
				purpose: file.purpose,
				coAuthor: coAuthorHeader.text,
				action: "created",
			});

			// 立即追加到 index.vue
			const pageDir = path.join(viewsDir, args.pageName);
			appendComponentToIndex(pageDir, componentName);

			fileIndex++;
		}

		if (skippedRouterFiles.length > 0) {
			console.log(`[ai-direct-apply-output] 跳过路由文件: ${skippedRouterFiles.join(", ")}`);
		}
		console.log(`[ai-direct-apply-output] ✓ 管道控制: ${writtenFiles.length} 个组件写入 ${componentsDir}`);
	}
	// 非追加模式:保留原有逻辑
	else {
		for (const file of response.files || []) {
			const normalized = (file.path || "").replaceAll("\\", "/");
			if (routerFilePatterns.has(normalized)) {
				skippedRouterFiles.push(normalized);
				continue;
			}

			const targetPath = resolveTargetPath(projectRoot, file.path);
			ensureDir(path.dirname(targetPath));
			fs.writeFileSync(targetPath, file.content, "utf8");
			prependCoAuthorHeader(targetPath, coAuthorHeader.line);

			const relativePath = normalizePath(path.relative(repoRoot, targetPath));
			writtenFiles.push({
				path: relativePath,
				language: file.language,
				purpose: file.purpose,
			});
			attributionEntries.push({
				path: relativePath,
				language: file.language,
				purpose: file.purpose,
				coAuthor: coAuthorHeader.text,
				action: fs.existsSync(targetPath) ? "updated" : "created",
			});
		}

		if (skippedRouterFiles.length > 0) {
			console.log(`[ai-direct-apply-output] 跳过路由文件: ${skippedRouterFiles.join(", ")}`);
		}
	}

	if (skippedRouterFiles.length > 0) {
		console.log(`[ai-direct-apply-output] 跳过 AI 生成的路由文件(由模板提供): ${skippedRouterFiles.join(", ")}`);
	}

	// 追加模式:生成组合父组件
	if (args.appendMode && writtenFiles.length > 0) {
		const parentResult = generateModuleParentComponent(projectRoot, writtenFiles);
		if (parentResult) {
			console.log(`[ai-direct-apply-output] ✓ 生成组合父组件: ${parentResult.path} (${parentResult.moduleCount} 个模块)`);
			writtenFiles.push({
				path: parentResult.path,
				language: "vue",
				purpose: "auto-generated parent component for module composition",
			});
		}
	}

	// 确保所有有 components/ 的页面目录都有 index.vue,然后再注册路由
	ensurePageIndexForPageDirs(projectRoot);
	const routerResult = registerRoutesInRouter(projectRoot);
	if (routerResult.count > 0) {
		console.log(`[ai-direct-apply-output] 自动注册路由: ${routerResult.count} 个新页面`);
		const routerFilePath = normalizePath(path.relative(repoRoot, routerResult.routerFile));
		writtenFiles.push({
			path: routerFilePath,
			language: "typescript",
			purpose: "auto-registered new views in router",
		});
	}

	const autoFixResults = runAutoFix(writtenFiles);
	const failedAutoFix = autoFixResults.filter((item) => !item.ok);
	if (failedAutoFix.length > 0) {
		_warn("[ai-direct-apply-output] warning: 自动修复未完全通过,校验阶段将继续暴露剩余问题");
		for (const item of failedAutoFix) {
			_warn(`  - ${item.command} (exit=${item.exitCode})`);
		}
	}

	// 写入 AI 归因清单
	const attributionPath = writeAttributionManifest(projectRoot, attributionEntries, args.model, args.provider);
	console.log(`[ai-direct-apply-output] ✓ AI 归因清单已写入: ${normalizePath(path.relative(repoRoot, attributionPath))}`);

	const summary = {
		meta: {
			generator: "scripts/ai-direct-apply-output.mjs",
			generatedAt: new Date().toISOString(),
			responseFile: normalizePath(responsePath),
			previewFile: normalizePath(previewPath),
		},
		attribution: {
			model: args.model || "unknown",
			provider: args.provider || "unknown",
			coAuthorHeader: coAuthorHeader.text,
			attributionFile: normalizePath(path.relative(repoRoot, attributionPath)),
			fileCount: attributionEntries.length,
		},
		result: {
			projectRoot: normalizePath(projectRoot),
			writtenFiles,
			autoFixResults,
			dependencyPlan: response.dependencyPlan,
			notes: response.notes,
			validationChecklist: response.validationChecklist,
		},
	};

	const summaryPath = path.join(
		path.dirname(responsePath),
		`${path.basename(responsePath, path.extname(responsePath))}.apply-result.json`,
	);
	fs.writeFileSync(summaryPath, `${JSON.stringify(summary, null, 2)}\n`, "utf8");

	console.log("[ai-direct-apply-output] ✓ 完成");
	console.log(`  → written files: ${writtenFiles.length}`);
	if (writtenFiles.length > 0) {
		console.log(`  → 文件列表:`);
		for (const file of writtenFiles) {
			console.log(`      - ${file.path} (${file.language}, ${file.purpose})`);
		}
	} else {
		_warn(`[ai-direct-apply-output] ⚠ 没有写入任何文件,AI 可能没有生成有效内容`);
	}
	console.log(`  → AI 归因: ${attributionEntries.length} 个文件已标记 co-author`);
	console.log(`  → summary: ${summaryPath}`);
}

run();
process.exit(0);