parse-docs.js 58.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 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
/**
 * 文档解析脚本
 *
 * @description 扫描 docs/to-parse 文件夹中的文档,调用 AI 服务解析,自动更新配置
 * @module scripts/parse-docs
 * @author Claude Code
 * @created 2026-02-13
 *
 * @usage
 * # 解析所有待处理文档
 * npm run parse:docs
 *
 * # 解析指定文档
 * npm run parse:docs -- --file=产品说明书.pdf
 *
 * # 查看待处理文档
 * npm run parse:docs -- --list
 *
 * # 应用审核通过的配置
 * npm run parse:docs -- --apply=计划书模版4
 *
 * # 预览应用配置(不实际修改)
 * npm run parse:docs -- --apply=计划书模版4 --dry-run
 */
import crypto from 'crypto'
import fs from 'fs'
import path from 'path'
import { PDFParse } from 'pdf-parse'
import mammoth from 'mammoth'
import Ajv from 'ajv'
import { spawn } from 'child_process'
import {
  checkMarkitdownAvailable,
  checkAIServiceConfigured,
  printConfigStatus,
  MARKITDOWN_CONFIG,
  AI_SERVICE_CONFIG
} from './parse-config.js'
import { smartExtractFields, smartExtractFieldsForProduct, generateAuditReport } from './smart-field-extractor.js'
import { splitByProducts, findProductTitles, generateSplitReport } from './product-splitter.js'

// ========== 配置区 ==========

const DOCS_DIR = path.resolve(process.cwd(), 'docs/to-parse')
const DOCS_ARCHIVE_DIR = path.resolve(process.cwd(), 'docs/to-parse/archived')
const CONFIG_FILE = path.resolve(process.cwd(), 'src/config/plan-templates.js')
const BACKUP_DIR = path.resolve(process.cwd(), 'docs/parsed-backup')

// 支持的文档格式
const SUPPORTED_EXTENSIONS = ['.pdf', '.doc', '.docx', '.txt', '.md']

const ajv = new Ajv({ allErrors: true, strict: false })
const parseConfigSchema = {
    type: 'object',
    required: ['product_name', 'product_type', 'currency', 'form_schema', 'submit_mapping'],
    properties: {
        product_name: { type: 'string', minLength: 1 },
        product_type: { type: 'string', enum: ['savings', 'life-insurance', 'critical-illness'] },
        currency: { type: 'string', minLength: 1 },
        form_schema: { type: 'object' },
        submit_mapping: { type: 'object' }
    },
    additionalProperties: true
}
const validateParsedConfigSchema = ajv.compile(parseConfigSchema)

// ========== 工具函数 ==========

/**
 * 确保目录存在
 */
function ensureDir(dirPath) {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true })
    console.log(`📁 创建目录: ${dirPath}`)
  }
}

/**
 * 读取文件内容
 */
function readFile(filePath) {
  return fs.readFileSync(filePath, 'utf-8')
}

function getFileMeta(filePath, extraMeta = {}) {
  const stats = fs.existsSync(filePath) ? fs.statSync(filePath) : { size: 0 }
  return {
    file_name: path.basename(filePath),
    ext: path.extname(filePath).toLowerCase(),
    size: stats.size,
    ocr: {
      enabled: false,
      provider: null,
      reason: 'not_configured'
    },
    ...extraMeta
  }
}

function buildArchiveFilePath(fileName) {
  const date = new Date().toISOString().split('T')[0]
  const archiveDir = path.join(DOCS_ARCHIVE_DIR, date)
  ensureDir(archiveDir)
  let targetPath = path.join(archiveDir, fileName)
  if (fs.existsSync(targetPath)) {
    const ext = path.extname(fileName)
    const baseName = path.basename(fileName, ext)
    targetPath = path.join(archiveDir, `${baseName}-${Date.now()}${ext}`)
  }
  return targetPath
}

function archiveParsedFile(filePath) {
  if (!fs.existsSync(filePath)) {
    return null
  }
  ensureDir(DOCS_ARCHIVE_DIR)
  const archivePath = buildArchiveFilePath(path.basename(filePath))
  fs.renameSync(filePath, archivePath)
  return archivePath
}

function buildExtractResult(filePath, text, warnings = [], extraMeta = {}) {
  return {
    text,
    warnings,
    meta: getFileMeta(filePath, extraMeta)
  }
}

async function extractTextFromPdf(filePath) {
  const buffer = fs.readFileSync(filePath)
  const parser = new PDFParse({ data: buffer })
  let result
  try {
    result = await parser.getText()
  } finally {
    await parser.destroy()
  }
  return buildExtractResult(filePath, result?.text || '', [], {
    total_pages: result?.total || 0
  })
}

async function extractTextFromDocx(filePath) {
  const buffer = fs.readFileSync(filePath)
  const result = await mammoth.extractRawText({ buffer })
  const warnings = (result.messages || []).map(item => `${item.type || 'warning'}:${item.message}`)
  return buildExtractResult(filePath, result.value || '', warnings)
}

function extractTextFromDoc(filePath) {
  return buildExtractResult(filePath, '', ['暂不支持 .doc,请转换为 .docx'])
}

function extractTextFromPlainFile(filePath) {
  return buildExtractResult(filePath, readFile(filePath), [])
}

export async function extractDocumentText(filePath) {
  const ext = path.extname(filePath).toLowerCase()
  let result

  if (ext === '.pdf') {
    result = await extractTextFromPdf(filePath)
  } else if (ext === '.docx') {
    result = await extractTextFromDocx(filePath)
  } else if (ext === '.doc') {
    result = extractTextFromDoc(filePath)
  } else if (ext === '.txt' || ext === '.md') {
    result = extractTextFromPlainFile(filePath)
  } else {
    result = buildExtractResult(filePath, '', [`不支持的文件类型: ${ext}`])
  }

  if (!result.text || !result.text.trim()) {
    result.warnings.push('抽取文本为空,可能是扫描件')
    result.meta.ocr = {
      enabled: false,
      provider: null,
      reason: 'text_empty'
    }
  }

  return result
}

export function validateParsedConfig(config) {
    const valid = validateParsedConfigSchema(config)
    if (valid) {
        return { valid: true, errors: [] }
    }

    const errors = (validateParsedConfigSchema.errors || []).map(error => {
        if (error.keyword === 'required' && error.params?.missingProperty) {
            return `${error.instancePath || '/'} 缺少字段 ${error.params.missingProperty}`
        }
        if (error.message) {
            return `${error.instancePath || '/'} ${error.message}`.trim()
        }
        return `${error.instancePath || '/'} 校验失败`
    })

    return { valid: false, errors }
}

/**
 * 写入文件内容
 */
function writeFile(filePath, content) {
  fs.writeFileSync(filePath, content, 'utf-8')
}

/**
 * 获取所有待处理的文档
 */
function getDocsToParse() {
  if (!fs.existsSync(DOCS_DIR)) {
    console.log('📂 文档夹不存在:', DOCS_DIR)
    return []
  }

  const files = fs.readdirSync(DOCS_DIR)
  return files
    .filter(file => SUPPORTED_EXTENSIONS.includes(path.extname(file).toLowerCase()))
    .filter(file => file !== 'README.md')
    .map(file => ({
      name: file,
      fullPath: path.join(DOCS_DIR, file),
      ext: path.extname(file).toLowerCase(),
      size: fs.statSync(path.join(DOCS_DIR, file)).size
    }))
}

/**
 * 生成 form_sn
 */
export function generateFormSn(config) {
    if (config?.form_sn) {
        return config.form_sn
    }

    const product_type = config?.product_type || 'product'
    const raw_name = (config?.product_name || '').trim()
    const name_slug = raw_name
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+|-+$/g, '')
    const base_value = `${product_type}|${name_slug || 'product'}|${raw_name}`
    const hash = crypto.createHash('sha1').update(base_value).digest('hex').slice(0, 8)

    return `${product_type}-${name_slug || 'product'}-${hash}`
}

/**
 * 生成配置代码
 */
export function generateConfigCode(config) {
    const formSn = generateFormSn(config)
    const isSavings = config.is_savings || config.product_type === 'savings'
    const productType = config.product_type || 'life-insurance'
    const componentName = isSavings
        ? 'SavingsTemplate'
        : (productType === 'critical-illness' ? 'CriticalIllnessTemplate' : 'LifeInsuranceTemplate')
    const { form_schema_ref, submit_mapping_ref } = resolveSchemaRefs(config)
    const form_schema_code = buildSchemaCode(config.form_schema, form_schema_ref)
    const submit_mapping_code = buildSchemaCode(config.submit_mapping, submit_mapping_ref)

    let code = "  /**\n"
    code += "   * " + config.product_name + "\n"
    code += "   * @added " + new Date().toISOString() + "\n"
    code += "   * @source docs/to-parse/" + config.source_file + "\n"
    code += "   */\n"
    code += "  '" + formSn + "': {\n"
    code += "    name: '" + config.product_name + "',\n"
    code += "    component: '" + componentName + "',\n"
    if (isSavings) {
        code += "    category: 'savings',\n"
    }
    code += "    config: {\n"

    if (isSavings) {
        code += "      currency: '" + config.currency + "',\n"
        code += "      payment_periods: " + JSON.stringify(config.payment_periods || []) + ",\n"
        code += "      age_range: { min: " + (config.age_range?.min || 0) + ", max: " + (config.age_range?.max || 75) + " },\n"
        code += "      insurance_period: '" + (config.insurance_period || '终身') + "',\n"
        code += "      withdrawal_plan: {\n"
        code += "        enabled: true,\n"
        code += "        currencies: ['HKD', 'USD', 'CNY'],\n"
        code += "        default_currency: '" + config.currency + "',\n"
        code += "        withdrawal_modes: " + JSON.stringify(config.withdrawal_modes || []) + ",\n"
        code += "        withdrawal_periods: " + JSON.stringify(config.withdrawal_periods || []) + "\n"
        code += "      },\n"
        code += "      form_schema: " + form_schema_code + ",\n"
        code += "      submit_mapping: " + submit_mapping_code + "\n"
    } else {
        code += "      currency: '" + config.currency + "',\n"
        code += "      payment_periods: " + JSON.stringify(config.payment_periods || []) + ",\n"
        code += "      age_range: { min: " + (config.age_range?.min || 0) + ", max: " + (config.age_range?.max || 75) + " },\n"
        code += "      insurance_period: '" + (config.insurance_period || '终身') + "',\n"
        code += "      form_schema: " + form_schema_code + ",\n"
        code += "      submit_mapping: " + submit_mapping_code + "\n"
    }

    code += "    }\n"
    code += "  }\n\n"

    return { formSn, code }
}

function resolveSchemaRefs(config) {
    const isSavings = config?.is_savings || config?.product_type === 'savings'
    if (isSavings) {
        return {
            form_schema_ref: 'savingsFormSchema',
            submit_mapping_ref: 'savingsSubmitMapping'
        }
    }
    return {
        form_schema_ref: 'protectionFormSchema',
        submit_mapping_ref: 'baseSubmitMapping'
    }
}

function buildSchemaCode(value, fallbackRef) {
    if (!value || isEmptyObject(value)) {
        return fallbackRef
    }
    if (value && typeof value === 'object' && !Array.isArray(value)) {
        const baseFields = value.base_fields
        const withdrawalFields = value.withdrawal_fields
        const resetMap = value.reset_map
        const baseFieldsEmpty = Array.isArray(baseFields) && baseFields.length === 0
        const withdrawalFieldsEmpty = !Array.isArray(withdrawalFields) || withdrawalFields.length === 0
        const resetMapEmpty = !resetMap || (typeof resetMap === 'object' && !Array.isArray(resetMap) && Object.keys(resetMap).length === 0)
        if (baseFieldsEmpty && withdrawalFieldsEmpty && resetMapEmpty) {
            return fallbackRef
        }
    }
    if (typeof value === 'string') {
        return value
    }
    return JSON.stringify(value, null, 2).replace(/\n/g, '\n      ')
}

function isEmptyObject(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return false
    }
    return Object.keys(value).length === 0
}

function formatSize(size) {
    if (size < 1024) return `${size} B`
    if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`
    if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(1)} MB`
    return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`
}

/**
 * 调用 markitdown 服务解析文档
 *
 * @description 使用 markitdown CLI 将 PDF/DOCX 转换为 Markdown/文本
 * @param {string} docPath - 文档路径
 * @returns {Promise<{text: string, warnings: string[]}>} 解析结果
 */
async function parseDocumentWithMarkitdown(docPath) {
  const ext = path.extname(docPath).toLowerCase()

  // MD 和 TXT 文件直接读取,不需要 markitdown
  if (ext === '.md' || ext === '.txt') {
    console.log(`📄 直接读取文本文件: ${path.basename(docPath)}`)
    return buildExtractResult(docPath, fs.readFileSync(docPath, 'utf-8'), [])
  }

  console.log(`\n📄 使用 markitdown 解析: ${path.basename(docPath)}`)

  try {
    if (MARKITDOWN_CONFIG.type === 'cli') {
      // .docx 文件使用 mammoth 库(markitdown 兼容性问题)
      if (ext === '.docx') {
        console.log('⚠️  .docx 文件使用 mammoth 库解析(避免 markitdown 兼容性问题)')
        return await extractTextFromDocx(docPath)
      }
      // 只对 PDF 使用 markitdown
      if (ext === '.pdf') {
        return await parseWithMarkitdownCLI(docPath)
      } else {
        console.log(`⚠️  文件类型 ${ext} 不支持 markitdown,使用本地库解析`)
        return await extractDocumentText(docPath)
      }
    }

    // 其他类型暂未实现,fallback 到本地库
    console.log('⚚️  markitdown 未启用,使用本地库解析')
    return await extractDocumentText(docPath)
  } catch (error) {
    console.error(`❌ markitdown 解析失败 (${docPath}):`, error.message)
    // fallback 到本地库
    console.log('🔄 回退到本地库解析...')
    return await extractDocumentText(docPath)
  }
}

/**
 * 使用 markitdown CLI 解析文档
 *
 * @description 使用 spawn 调用 markitdown CLI 工具(从 stdin 读取)
 * @param {string} docPath - 文档路径
 * @returns {Promise<{text: string, warnings: string[]}>} 解析结果
 */
async function parseWithMarkitdownCLI(docPath) {
  const tmpDir = path.resolve(process.cwd(), 'docs/tmp')
  ensureDir(tmpDir)

  const outputPath = path.join(tmpDir, path.basename(docPath, path.extname(docPath)) + '.md')
  const timeout = MARKITDOWN_CONFIG.cli.timeout || 30000

  console.log(`   命令: cat "${docPath}" | markitdown > "${outputPath}"`)

  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      spawn.kill(0, 'SIGTERM') // 尝试优雅终止
      reject(new Error('markitdown 执行超时'))
    }, timeout)

    // 使用 cat 读取文件并通过管道传递给 markitdown
    const cat = spawn('cat', [docPath])
    const markitdown = spawn('markitdown', [], {
      stdio: ['ignore', 'pipe', 'pipe']
    })

    let stdout = ''
    let stderr = ''

    markitdown.stdout.on('data', (data) => { stdout += data })
    markitdown.stderr.on('data', (data) => { stderr += data })

    markitdown.on('close', (code) => {
      clearTimeout(timer)

      if (code !== 0) {
        reject(new Error(`markitdown 退出码: ${code}\n${stderr}`))
        return
      }

      // 写入输出文件
      try {
        fs.writeFileSync(outputPath, stdout, 'utf-8')

        console.log(`✅ markitdown 解析成功,提取 ${stdout.length} 字符`)
        resolve({ text: stdout, warnings: [] })
      } catch (writeError) {
        reject(writeError)
      }
    })

    markitdown.on('error', (error) => {
      clearTimeout(timer)
      reject(error)
    })

    cat.on('error', (error) => {
      clearTimeout(timer)
      reject(error)
    })

    // 将 cat 的输出连接到 markitdown 的输入
    cat.stdout.pipe(markitdown.stdin)
  })
}

/**
 * AI 解析提示词模板
 *
 * @description 用于指导 AI 从文档内容中提取产品配置
 */
const AI_PARSE_PROMPT = `你是一个保险产品配置专家。请从以下文档内容中提取产品配置信息。

请按以下 JSON 格式返回配置:
{
  "product_name": "产品名称",
  "product_type": "产品类型 (savings/life-insurance/critical-illness)",
  "currency": "币种 (USD/CNY/HKD)",
  "payment_periods": ["缴费年期1", "缴费年期2"],
  "age_range": { "min": 最小年龄, "max": 最大年龄 },
  "insurance_period": "保险期间",
  "is_savings": true/false (是否为储蓄型产品),
  "withdrawal_modes": ["提取模式1", "提取模式2"],
  "withdrawal_periods": ["提取期1", "提取期2"]
}

文档内容:
{CONTENT}

请只返回 JSON,不要包含其他内容。`

/**
 * 调用 AI 服务解析文档
 *
 * @description 使用 markitdown + AI 智能解析文档并提取配置
 * @param {string} docPath - 文档路径
 * @returns {Promise<Object|Array<Object>>} 解析后的配置对象或配置数组(多产品)
 */
async function parseDocumentWithAI(docPath) {
  console.log(`\n🤖 正在智能解析: ${path.basename(docPath)}`)

  try {
    // 步骤 1: 使用 markitdown 将文档转换为 Markdown/文本
    const parse_result = await parseDocumentWithMarkitdown(docPath)

    if (parse_result.warnings.length > 0) {
      parse_result.warnings.forEach(message => {
        console.log(`⚠️  解析警告: ${message}`)
      })
    }

    if (!parse_result.text || !parse_result.text.trim()) {
      console.error(`❌ 文档解析失败,文本为空 (${docPath})`)
      return null
    }

    const content = parse_result.text
    const fileName = path.basename(docPath)

    // ========== 步骤 2: 检测并分割多产品 ==========
    const productTitles = findProductTitles(content)

    if (productTitles.length > 1) {
      // 多产品文档
      console.log(`\n📦 检测到 ${productTitles.length} 个产品:`)
      productTitles.forEach((p, i) => {
        console.log(`   ${i + 1}. [${p.code || '?'}] ${p.name || p.fullTitle?.slice(0, 30)}`)
      })

      // 分割文档
      const products = splitByProducts(content)
      const splitReport = generateSplitReport(content, products)
      console.log('\n' + splitReport)

      // 对每个产品分别提取字段
      const configs = []
      for (let i = 0; i < products.length; i++) {
        const product = products[i]
        console.log(`\n${'='.repeat(40)}`)
        console.log(`📋 处理产品 ${i + 1}/${products.length}: ${product.name || product.code || '未命名'}`)
        console.log('='.repeat(40))

        const extractResult = smartExtractFieldsForProduct(
          product.content,
          fileName,
          {
            productCode: product.code,
            productName: product.name
          }
        )

        // 生成审核报告
        const auditReport = generateAuditReport(extractResult)
        console.log('\n' + auditReport)

        // 构建配置对象
        const config = {
          ...extractResult.config,
          is_savings: extractResult.config.product_type === 'savings',
          form_schema: { base_fields: [], withdrawal_fields: [], reset_map: {} },
          submit_mapping: {}
        }

        // 保存匹配详情
        config._extractDetails = {
          matched: extractResult.matchDetails.filter(m => m.matched).map(m => m.field),
          unmatched: extractResult.unmatched,
          warnings: extractResult.warnings,
          productIndex: i,
          totalProducts: products.length
        }

        config.form_sn = generateFormSn(config)

        const matchedCount = extractResult.matchDetails.filter(m => m.matched).length
        const totalCount = extractResult.matchDetails.length

        console.log(`\n✅ 产品 ${i + 1} 解析成功 (智能匹配 ${matchedCount}/${totalCount} 字段)`)
        console.log(`   产品名称: ${config.product_name}`)
        console.log(`   产品代码: ${product.code || '-'}`)
        console.log(`   产品类型: ${config.product_type}`)
        console.log(`   币种: ${config.currency}`)
        console.log(`   缴费年期: ${JSON.stringify(config.payment_periods)}`)

        configs.push(config)
      }

      return configs // 返回数组
    }

    // ========== 单产品文档 ==========
    console.log('🧠 使用智能字段提取器...')
    const extractResult = smartExtractFields(content, fileName)

    // 生成审核报告
    const auditReport = generateAuditReport(extractResult)
    console.log('\n' + auditReport)

    // 构建配置对象
    const config = {
      ...extractResult.config,
      is_savings: extractResult.config.product_type === 'savings',
      form_schema: { base_fields: [], withdrawal_fields: [], reset_map: {} },
      submit_mapping: {}
    }

    // 保存匹配详情供后续审核使用
    config._extractDetails = {
      matched: extractResult.matchDetails.filter(m => m.matched).map(m => m.field),
      unmatched: extractResult.unmatched,
      warnings: extractResult.warnings
    }

    config.form_sn = generateFormSn(config)

    const matchedCount = extractResult.matchDetails.filter(m => m.matched).length
    const totalCount = extractResult.matchDetails.length

    console.log(`\n✅ 解析成功 (智能匹配 ${matchedCount}/${totalCount} 字段)`)
    console.log(`   产品名称: ${config.product_name}`)
    console.log(`   产品类型: ${config.product_type}`)
    console.log(`   币种: ${config.currency}`)
    console.log(`   缴费年期: ${JSON.stringify(config.payment_periods)}`)

    if (extractResult.unmatched.length > 0) {
      console.log(`\n⚠️  需要人工补充 ${extractResult.unmatched.length} 个字段,详见审核文件`)
    }

    return config
  } catch (error) {
    console.error(`❌ 解析失败 (${docPath}):`, error.message)
    return null
  }
}

/**
 * 启发式推断产品类型
 *
 * @description 从文件名和内容推断产品类型
 * @param {string} fileName - 文件名
 * @param {string} content - 文档内容
 * @returns {string} 产品类型
 */
function inferProductType(fileName, content) {
  const lowerName = fileName.toLowerCase()

  if (lowerName.includes('储蓄') || lowerName.includes('saving') || lowerName.includes('传承') || lowerName.includes('家传')) {
    return 'savings'
  }
  if (lowerName.includes('重疾') || lowerName.includes('critical') || lowerName.includes('守护')) {
    return 'critical-illness'
  }
  if (lowerName.includes('人寿') || lowerName.includes('life') || lowerName.includes('创富')) {
    return 'life-insurance'
  }

  // 从内容中推断
  const contentLower = content.toLowerCase()
  if (contentLower.includes('储蓄') || contentLower.includes('红利') || contentLower.includes('提取')) {
    return 'savings'
  }
  if (contentLower.includes('重疾') || contentLower.includes('早期严重疾病')) {
    return 'critical-illness'
  }
  if (contentLower.includes('寿险') || contentLower.includes('身故保障')) {
    return 'life-insurance'
  }

  // 默认为储蓄型
  return 'savings'
}

/**
 * 启发式推断币种
 *
 * @description 从文档内容推断币种
 * @param {string} content - 文档内容
 * @returns {string} 币种代码
 */
function inferCurrency(content) {
  // 统计各种币种符号的出现次数
  const usdCount = (content.match(/\$/g) || []).length
  const cnyCount = (content.match(/¥|人民币/g) || []).length
  const hkdCount = (content.match(/HK\$/g) || []).length

  if (usdCount > cnyCount && usdCount > hkdCount) return 'USD'
  if (hkdCount > usdCount && hkdCount > cnyCount) return 'HKD'
  if (cnyCount > usdCount && cnyCount > hkdCount) return 'CNY'

  // 默认美元
  return 'USD'
}

/**
 * 解析单个文档
 *
 * @description 支持单产品和多产品文档解析
 * - 单产品文档:返回单个结果对象
 * - 多产品文档:返回结果数组(每个产品一个结果)
 */
async function parseSingleFile(filePath) {
  const fileName = path.basename(filePath)
  console.log("\n" + "=".repeat(60))
  console.log("📄 处理文件: " + fileName)
  console.log("=".repeat(60))

  // 解析文档(可能返回单个 config 或 configs 数组)
  const parseResult = await parseDocumentWithAI(filePath)

  if (!parseResult) {
    console.log("⏭️  跳过文件: " + fileName + " (解析失败)")
    return { success: false, file: fileName, reason: 'parse_failed' }
  }

  // 统一处理为数组形式
  const configs = Array.isArray(parseResult) ? parseResult : [parseResult]

  // 多产品提示
  if (configs.length > 1) {
    console.log("\n📦 检测到多产品文档,共 " + configs.length + " 个产品")
  }

  // 处理每个产品配置
  const results = []
  for (let i = 0; i < configs.length; i++) {
    const config = configs[i]
    const productIndex = configs.length > 1 ? ` [${i + 1}/${configs.length}]` : ''

    if (configs.length > 1 && config.product_name) {
      console.log("\n--- 处理产品: " + config.product_name + " ---")
    }

    const validation = validateParsedConfig(config)
    if (!validation.valid) {
      console.error("❌ 校验失败" + productIndex + ": " + (config.product_name || fileName))
      validation.errors.forEach(message => {
        console.error(" - " + message)
      })
      results.push({
        success: false,
        file: fileName,
        productName: config.product_name || `产品${i + 1}`,
        reason: 'validation_failed',
        errors: validation.errors
      })
      continue
    }

    // 添加源文件信息
    config.source_file = fileName

    // 生成配置代码
    const { formSn, code } = generateConfigCode(config)

    console.log("\n📝 生成 form_sn: " + formSn + productIndex)
    console.log("📋 生成配置代码:\n" + code)

    // 生成待审核文件
    const auditFile = await generateAuditFile(fileName, config, code, i, configs.length)
    if (auditFile) {
      console.log("\n✅ 已生成待审核文件: " + auditFile)
      console.log("📋 请审核后手动移动到 src/config/plan-templates.js")
    }

    results.push({
      success: true,
      formSn,
      code,
      file: fileName,
      productName: config.product_name || `产品${i + 1}`,
      config,
      auditFile
    })
  }

  const shouldArchive = results.length > 0 && results.every(r => r.success)
  if (shouldArchive) {
    const archivedPath = archiveParsedFile(filePath)
    if (archivedPath) {
      console.log("📦 已归档原始文档: " + archivedPath)
    }
  }

  // 单产品时返回单个结果对象(保持向后兼容)
  // 多产品时返回数组
  if (configs.length === 1) {
    return results[0]
  }

  // 多产品返回特殊结构
  return {
    success: results.some(r => r.success),
    file: fileName,
    multiProduct: true,
    productCount: configs.length,
    successCount: results.filter(r => r.success).length,
    results // 每个产品的详细结果
  }
}

/**
 * 生成待审核文件
 *
 * @description 生成人类可读的 markdown 审核文件,保存到 docs/parse-audit/pending/
 * @param {string} fileName - 原始文件名
 * @param {Object} config - 解析的配置对象
 * @param {string} code - 生成的配置代码
 * @param {number} productIndex - 产品索引(多产品文档时使用,从 0 开始)
 * @param {number} totalProducts - 产品总数(多产品文档时使用)
 * @returns {Promise<string|null>} 审核文件路径
 */
async function generateAuditFile(fileName, config, code, productIndex = 0, totalProducts = 1) {
  const AUDIT_PENDING_DIR = path.resolve(process.cwd(), 'docs/parse-audit/pending')
  const AUDIT_APPROVED_DIR = path.resolve(process.cwd(), 'docs/parse-audit/approved')
  ensureDir(AUDIT_PENDING_DIR)
  ensureDir(AUDIT_APPROVED_DIR)

  const date = new Date().toISOString().split('T')[0]
  const baseFileName = fileName.replace(/\.[^/.]+$/, '')
  const pendingDir = path.join(AUDIT_PENDING_DIR, baseFileName)
  ensureDir(pendingDir)

  // 多产品文档时,为每个产品生成独立文件
  let auditFileName
  if (totalProducts > 1 && config.product_name) {
    // 使用产品名称作为文件名的一部分
    const productSlug = config.product_name
      .replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '-') // 保留中文、英文、数字
      .replace(/-+/g, '-')
      .slice(0, 30) // 限制长度
    auditFileName = `${date}-${baseFileName}-${productSlug}.md`
  } else {
    auditFileName = `${date}-${baseFileName}.md`
  }
  const auditFilePath = path.join(pendingDir, auditFileName)
  const formSn = generateFormSn(config)
  const formSchemaPreview = config.form_schema ? JSON.stringify(config.form_schema, null, 2) : '// 请手动补充'
  const submitMappingPreview = config.submit_mapping ? JSON.stringify(config.submit_mapping, null, 2) : '// 请手动补充'
  const configPreview = {
    product_name: config.product_name || '',
    product_type: config.product_type || '',
    currency: config.currency || '',
    form_sn: formSn,
    payment_periods: config.payment_periods || [],
    age_range: config.age_range || { min: 0, max: 75 },
    insurance_period: config.insurance_period || '终身',
    is_savings: config.is_savings || config.product_type === 'savings',
    withdrawal_modes: config.withdrawal_modes || [],
    withdrawal_periods: config.withdrawal_periods || []
  }

  // 生成字段提取报告
  let extractionReport = ''
  if (config._extractDetails) {
    const { matched, unmatched, warnings } = config._extractDetails

    extractionReport = `
---

## 🤖 智能字段提取报告

### 匹配统计

- ✅ 成功匹配: ${matched.length} 字段
- ⚠️  使用默认值: ${warnings.length} 字段
- ❌ 未匹配(需人工补充): ${unmatched.length} 字段

### ✅ 已成功匹配的字段

${matched.map(f => `- ${f}`).join('\n') || '- (无)'}

${warnings.length > 0 ? `
### ⚠️  使用默认值的字段

${warnings.map(w => `- **${w.field}**: ${w.message}`).join('\n')}
` : ''}

${unmatched.length > 0 ? `
### ❌ 未匹配字段(需要人工补充)

${unmatched.map(item => `
#### ${item.field}

- **原因**: ${item.reason}
- **建议值**:
${item.suggestions.map(s => `  - ${s}`).join('\n')}
`).join('\n')}
` : ''}
`
  }

  const content = `# 产品配置审核 - ${fileName}

**解析时间**: ${new Date().toLocaleString('zh-CN')}
**原始文件**: ${fileName}
**数据来源**: docs/to-parse/${fileName}

---

## 📋 产品基本信息

| 字段 | 提取值 | 需要确认 |
|------|--------|---------|
| 产品名称 | ${config.product_name || '未提取'} | ✅ 请核对产品名称 |
| 产品类型 | ${config.product_type || '未提取'} | ✅ 请确认产品类型 |
| 币种 | ${config.currency || 'USD'} | ✅ 请确认币种 |
| form_sn | \`${formSn}\` | ✅ 请确认 form_sn 唯一性 |
| 缴费年期 | ${JSON.stringify(config.payment_periods || [])} | ✅ 请确认缴费年期选项 |
| 年龄范围 | ${config.age_range?.min || 0}-${config.age_range?.max || 75} |  请确认年龄范围 |
| 保险期间 | ${config.insurance_period || '终身'} |  请确认保险期间 |

${config.is_savings ? `
### 💰 储蓄类产品特有字段

| 字段 | 提取值 | 需要确认 |
|------|--------|---------|
| 提取方式 | ${JSON.stringify(config.withdrawal_modes || [])} | ✅ 请确认提取方式 |
| 提取期 | ${JSON.stringify(config.withdrawal_periods || [])} | ✅ 请确认提取期选项 |
` : ''}
${extractionReport}
---

## 🧾 配置预览

\`\`\`javascript
${JSON.stringify(configPreview, null, 2)}
\`\`\`

---

## 📝 表单字段 (form_schema)

\`\`\`javascript
${formSchemaPreview}
\`\`\`

---

## 🔄 提交字段映射 (submit_mapping)

\`\`\`javascript
${submitMappingPreview}
\`\`\`

---

## 🧩 生成配置片段

\`\`\`javascript
${code.trim()}
\`\`\`

---

## ✅ 审核检查清单

### 基础信息
- [ ] 产品名称正确
- [ ] 产品类型正确(savings/critical-illness/life-insurance)
- [ ] 币种正确(USD/CNY/HKD/EUR)
- [ ] form_sn 唯一且符合命名规范

### 缴费与年龄
- [ ] 缴费年期选项完整且正确
- [ ] 年龄范围合理
- [ ] 保险期间正确

### 储蓄类特有(如适用)
- [ ] 提取方式正确
- [ ] 提取期选项完整
- [ ] 表单字段定义完整
- [ ] 提交字段映射正确

---

## 📋 审核后操作

### 方法 1:自动应用(推荐)
\`\`\`bash
# 预览变更(不实际修改)
pnpm parse:docs -- --apply=${baseFileName} --dry-run

# 确认无误后,正式应用
pnpm parse:docs -- --apply=${baseFileName}

# 说明:
# 1. 自动提取配置代码并插入到 src/config/plan-templates.js
# 2. 自动创建备份文件(docs/parsed-backup/)
# 3. 自动将审核文件移动到 docs/parse-audit/approved/
\`\`\`

### 方法 2:手动操作
\`\`\`bash
# 1. 移动到 approved 目录
mv docs/parse-audit/pending/${baseFileName}/${auditFileName} \\
   docs/parse-audit/approved/

# 2. 手动复制"生成配置片段"到 src/config/plan-templates.js
\`\`\`

### 需要修改
1. 编辑本文件修正内容
2. 重新提交审核

### 放弃本次解析
\`\`\`bash
rm docs/parse-audit/pending/${baseFileName}/${auditFileName}
\`\`\`

---

## 审核状态

- [ ] 待审核
- [ ] 已通过
- [ ] 已拒绝

## 审核意见

\`\`\`text
\`\`\`
`

  try {
    fs.writeFileSync(auditFilePath, content, 'utf-8')
    return auditFilePath
  } catch (error) {
    console.error(`❌ 写入审核文件失败: ${error.message}`)
    return null
  }
}

/**
 * 更新配置文件
 * @description 使用简单的字符串搜索找到正确的插入位置
 */
export function updateConfigContent(existingContent, newConfigs) {
    const range = getPlanTemplatesRange(existingContent)
    if (!range) {
        return null
    }

    // 过滤掉没有 code 的配置项
    const validConfigs = newConfigs.filter(item => item && item.code)
    if (validConfigs.length === 0) {
        console.warn('⚠️  没有有效的配置代码可插入')
        return null
    }

    const insertContent = validConfigs.map((item, index) => {
        const code = item.code.trimEnd()
        return index === validConfigs.length - 1 ? code : code + ','
    }).join('\n\n')

    const before = existingContent.substring(0, range.endIndex)
    const after = existingContent.substring(range.endIndex)
    const beforeTrimmed = before.replace(/\s+$/, '')
    const needsComma = !beforeTrimmed.endsWith(',')
    const comma = needsComma ? ',' : ''

    return `${beforeTrimmed}${comma}\n\n${insertContent}${after}`
}

function getPlanTemplatesRange(content) {
    const startToken = 'export const PLAN_TEMPLATES = {'
    const startIndex = content.indexOf(startToken)
    if (startIndex === -1) {
        return null
    }

    const openIndex = startIndex + startToken.length - 1
    let depth = 1
    let inSingle = false
    let inDouble = false
    let inTemplate = false
    let escape = false

    for (let i = openIndex + 1; i < content.length; i += 1) {
        const ch = content[i]
        if (escape) {
            escape = false
            continue
        }
        if (ch === '\\') {
            if (inSingle || inDouble || inTemplate) {
                escape = true
            }
            continue
        }
        if (inSingle) {
            if (ch === "'") {
                inSingle = false
            }
            continue
        }
        if (inDouble) {
            if (ch === '"') {
                inDouble = false
            }
            continue
        }
        if (inTemplate) {
            if (ch === '`') {
                inTemplate = false
            }
            continue
        }
        if (ch === "'") {
            inSingle = true
            continue
        }
        if (ch === '"') {
            inDouble = true
            continue
        }
        if (ch === '`') {
            inTemplate = true
            continue
        }
        if (ch === '{') {
            depth += 1
            continue
        }
        if (ch === '}') {
            depth -= 1
            if (depth === 0) {
                return { startIndex, endIndex: i }
            }
        }
    }

    return null
}

function readQuotedKey(content, startIndex) {
    const quote = content[startIndex]
    let value = ''
    let escape = false
    for (let i = startIndex + 1; i < content.length; i += 1) {
        const ch = content[i]
        if (escape) {
            value += ch
            escape = false
            continue
        }
        if (ch === '\\') {
            escape = true
            continue
        }
        if (ch === quote) {
            return { value, endIndex: i }
        }
        value += ch
    }
    return null
}

function extractPlanTemplateKeys(content) {
    const range = getPlanTemplatesRange(content)
    if (!range) {
        return []
    }
    const block = content.slice(range.startIndex, range.endIndex + 1)
    const blockStart = block.indexOf('{') + 1
    const blockContent = block.slice(blockStart, block.length - 1)

    const keys = []
    let depth = 0
    let inSingle = false
    let inDouble = false
    let inTemplate = false
    let escape = false

    for (let i = 0; i < blockContent.length; i += 1) {
        const ch = blockContent[i]
        if (escape) {
            escape = false
            continue
        }
        if (ch === '\\') {
            if (inSingle || inDouble || inTemplate) {
                escape = true
            }
            continue
        }
        if (inSingle) {
            if (ch === "'") {
                inSingle = false
            }
            continue
        }
        if (inDouble) {
            if (ch === '"') {
                inDouble = false
            }
            continue
        }
        if (inTemplate) {
            if (ch === '`') {
                inTemplate = false
            }
            continue
        }
        if (ch === "'") {
            inSingle = true
            if (depth === 0) {
                const keyResult = readQuotedKey(blockContent, i)
                if (keyResult) {
                    const nextIndex = keyResult.endIndex + 1
                    const rest = blockContent.slice(nextIndex)
                    const match = rest.match(/^\s*:/)
                    if (match) {
                        keys.push(keyResult.value)
                    }
                    i = keyResult.endIndex
                    inSingle = false
                }
            }
            continue
        }
        if (ch === '"') {
            inDouble = true
            if (depth === 0) {
                const keyResult = readQuotedKey(blockContent, i)
                if (keyResult) {
                    const nextIndex = keyResult.endIndex + 1
                    const rest = blockContent.slice(nextIndex)
                    const match = rest.match(/^\s*:/)
                    if (match) {
                        keys.push(keyResult.value)
                    }
                    i = keyResult.endIndex
                    inDouble = false
                }
            }
            continue
        }
        if (ch === '`') {
            inTemplate = true
            continue
        }
        if (ch === '{') {
            depth += 1
            continue
        }
        if (ch === '}') {
            depth -= 1
        }
    }

    return keys
}

export function detectFormSnConflicts(existingContent, newConfigs) {
    const existingKeys = extractPlanTemplateKeys(existingContent)
    const existingSet = new Set(existingKeys)
    const conflicts = []
    newConfigs.forEach(item => {
        if (existingSet.has(item.formSn)) {
            conflicts.push(item.formSn)
        }
    })
    return conflicts
}

export function buildDryRunDiff(newConfigs) {
    const insertContent = newConfigs.map((item, index) => {
        const code = item.code.trimEnd()
        return index === newConfigs.length - 1 ? code : code + ','
    }).join('\n\n')
    const lines = insertContent.split('\n').map(line => `+ ${line}`)
    return ['--- plan-templates.js', '+++ plan-templates.js', ...lines].join('\n')
}

export function buildConfigUpdateResult(existingContent, newConfigs, options = {}) {
    const conflicts = detectFormSnConflicts(existingContent, newConfigs)
    if (conflicts.length > 0) {
        return { ok: false, conflicts, updatedContent: null, diff: null }
    }

    const updatedContent = updateConfigContent(existingContent, newConfigs)
    if (!updatedContent) {
        return { ok: false, conflicts: [], updatedContent: null, diff: null }
    }

    const diff = options.dry_run ? buildDryRunDiff(newConfigs) : null
    return { ok: true, conflicts: [], updatedContent, diff }
}

export function buildParseSummary(results, duration_ms) {
    const summary = {
        total_docs: results.length,
        total_products: 0,
        success: 0,
        failed: 0,
        duration_ms,
        success_list: [],
        failed_list: []
    }

    results.forEach(result => {
        // 处理多产品文档
        if (result.multiProduct) {
            summary.total_products += result.productCount

            if (result.results) {
                result.results.forEach(r => {
                    if (r.success) {
                        summary.success += 1
                        summary.success_list.push({
                            form_sn: r.formSn,
                            product_name: r.config?.product_name || r.productName,
                            file: r.file
                        })
                    } else {
                        summary.failed += 1
                        summary.failed_list.push({
                            file: r.file,
                            product_name: r.productName,
                            reason: r.reason || 'unknown',
                            errors: r.errors || []
                        })
                    }
                })
            }
        } else {
            // 单产品文档
            summary.total_products += 1

            if (result.success) {
                summary.success += 1
                summary.success_list.push({
                    form_sn: result.formSn,
                    product_name: result.config?.product_name,
                    file: result.file
                })
            } else {
                summary.failed += 1
                summary.failed_list.push({
                    file: result.file,
                    reason: result.reason || 'unknown',
                    errors: result.errors || []
                })
            }
        }
    })

    summary.total = summary.total_products
    return summary
}

function buildChangeSummary(update_result) {
    if (!update_result) {
        return null
    }
    const summary = {
        ok: update_result.ok,
        dry_run: update_result.dry_run || false,
        updated_count: update_result.updated_count || 0,
        form_sn_list: update_result.form_sn_list || [],
        conflicts: update_result.conflicts || [],
        reason: update_result.reason || null
    }

    if (update_result.diff) {
        summary.diff_preview = update_result.diff.split('\n').slice(0, 60).join('\n')
    }

    return summary
}

function buildAuditRecord(summary, options = {}, update_result = null, mode = 'batch') {
    return {
        at: new Date().toISOString(),
        mode,
        options: {
            dry_run: !!options.dry_run
        },
        summary,
        change_summary: buildChangeSummary(update_result)
    }
}

function writeBackupLog(record) {
    ensureDir(BACKUP_DIR)
    const logFile = path.join(BACKUP_DIR, 'backup-log.jsonl')
    const line = JSON.stringify(record)
    fs.appendFileSync(logFile, `${line}\n`, 'utf-8')
}

function writeAuditLog(record) {
    ensureDir(BACKUP_DIR)
    const logFile = path.join(BACKUP_DIR, 'parse-audit.jsonl')
    const line = JSON.stringify(record)
    fs.appendFileSync(logFile, `${line}\n`, 'utf-8')
}

function rollbackConfigFile(backupFile) {
    if (!backupFile || !fs.existsSync(backupFile)) {
        console.error("❌ 找不到备份文件: " + backupFile)
        return false
    }
    fs.copyFileSync(backupFile, CONFIG_FILE)
    writeBackupLog({
        action: 'rollback',
        backup_file: backupFile,
        target_file: CONFIG_FILE,
        at: new Date().toISOString()
    })
    console.log("✅ 已回滚配置文件: " + backupFile)
    return true
}

/**
 * 从审核文件应用配置到 plan-templates.js
 *
 * @description 读取审核 markdown 文件,提取配置代码,插入到配置文件中
 * @param {string} auditFileName - 审核文件名(不含路径,如 "计划书模版4")
 * @param {Object} options - 选项
 * @param {boolean} options.dry_run - 是否仅预览
 * @returns {Object} 应用结果
 */
function applyAuditFile(auditFileName, options = {}) {
    const PENDING_DIR = path.resolve(process.cwd(), 'docs/parse-audit/pending')
    const APPROVED_DIR = path.resolve(process.cwd(), 'docs/parse-audit/approved')

    // 1. 查找审核文件
    let auditFile = null
    let sourceDir = null

    // 先在 pending 目录查找
    const pendingDirs = fs.existsSync(PENDING_DIR) ? fs.readdirSync(PENDING_DIR) : []
    for (const dir of pendingDirs) {
        const dirPath = path.join(PENDING_DIR, dir)
        if (fs.statSync(dirPath).isDirectory()) {
            const files = fs.readdirSync(dirPath).filter(f => f.endsWith('.md'))
            for (const file of files) {
                // 匹配文件名或目录名
                const normalizedName = dir.replace(/\s+/g, '').toLowerCase()
                const normalizedInput = auditFileName.replace(/\s+/g, '').toLowerCase()
                if (normalizedName.includes(normalizedInput) || normalizedInput.includes(normalizedName)) {
                    auditFile = path.join(dirPath, file)
                    sourceDir = PENDING_DIR
                    break
                }
            }
        }
        if (auditFile) break
    }

    // 如果 pending 没找到,在 approved 目录查找
    if (!auditFile && fs.existsSync(APPROVED_DIR)) {
        const approvedFiles = fs.readdirSync(APPROVED_DIR).filter(f => f.endsWith('.md'))
        for (const file of approvedFiles) {
            // 从文件名提取产品名(格式:YYYY-MM-DD-产品名.md)
            const match = file.match(/^\d{4}-\d{2}-\d{2}-(.+)\.md$/)
            if (match) {
                const normalizedName = match[1].replace(/\s+/g, '').toLowerCase()
                const normalizedInput = auditFileName.replace(/\s+/g, '').toLowerCase()
                if (normalizedName.includes(normalizedInput) || normalizedInput.includes(normalizedName)) {
                    auditFile = path.join(APPROVED_DIR, file)
                    sourceDir = APPROVED_DIR
                    break
                }
            }
        }
    }

    if (!auditFile) {
        console.error("❌ 找不到审核文件: " + auditFileName)
        console.log("   搜索目录:")
        console.log("   - docs/parse-audit/pending/")
        console.log("   - docs/parse-audit/approved/")
        return { ok: false, reason: 'file_not_found' }
    }

    console.log("\n📄 找到审核文件: " + auditFile)

    // 2. 读取审核文件内容
    const content = fs.readFileSync(auditFile, 'utf-8')

    // 3. 提取配置代码片段
    const configMatch = content.match(/## 🧩 生成配置片段\s*\n+```javascript\s*\n([\s\S]*?)```/)
    if (!configMatch) {
        console.error("❌ 无法从审核文件中提取配置代码")
        return { ok: false, reason: 'config_not_found' }
    }

    const configCode = configMatch[1].trim()
    console.log("\n📝 提取的配置代码:")
    console.log("-".repeat(40))
    console.log(configCode)
    console.log("-".repeat(40))

    // 4. 提取 form_sn 用于去重检查
    const formSnMatch = configCode.match(/'([^']+)':\s*\{/)
    const formSn = formSnMatch ? formSnMatch[1] : null

    if (!formSn) {
        console.error("❌ 无法从配置代码中提取 form_sn")
        return { ok: false, reason: 'form_sn_not_found' }
    }

    console.log("\n🔑 form_sn: " + formSn)

    // 5. 读取现有配置文件
    const existingContent = fs.readFileSync(CONFIG_FILE, 'utf-8')

    // 检查是否已存在
    if (existingContent.includes(`'${formSn}':`)) {
        console.error("❌ 配置文件中已存在 form_sn: " + formSn)
        console.log("   如需更新,请先手动删除旧配置")
        return { ok: false, reason: 'duplicate', formSn }
    }

    // 6. 找到插入位置(PLAN_TEMPLATES 对象的结束位置)
    // 查找最后一个产品配置的结束位置
    const insertPattern = /(\n\s*'\w+[^']+':\s*\{[\s\S]*?\n\s*\}\s*,?\s*)(\n\})/
    const match = existingContent.match(insertPattern)

    if (!match) {
        console.error("❌ 无法定位插入位置")
        return { ok: false, reason: 'insert_not_found' }
    }

    // 7. 构建新配置(确保有逗号)
    let newConfigEntry = configCode
    // 确保配置以逗号结尾
    if (!newConfigEntry.trimEnd().endsWith(',')) {
        newConfigEntry = newConfigEntry.trimEnd() + ','
    }

    // 8. 插入配置
    const insertPosition = match.index + match[1].length
    const updatedContent =
        existingContent.slice(0, insertPosition) +
        '\n\n' +
        newConfigEntry +
        existingContent.slice(insertPosition)

    if (options.dry_run) {
        console.log("\n🧪 dry-run 模式,变更预览:")
        console.log("-".repeat(40))
        console.log("将插入以下配置:")
        console.log(newConfigEntry)
        console.log("-".repeat(40))
        return { ok: true, dry_run: true, formSn }
    }

    // 9. 备份并写入
    let backupFile = null
    if (fs.existsSync(CONFIG_FILE)) {
        ensureDir(BACKUP_DIR)
        backupFile = path.join(BACKUP_DIR, `plan-templates.backup.${Date.now()}.js`)
        fs.copyFileSync(CONFIG_FILE, backupFile)
        console.log("\n💾 已备份到: " + backupFile)
    }

    writeFile(CONFIG_FILE, updatedContent)
    console.log("\n✅ 配置已更新: " + CONFIG_FILE)

    writeBackupLog({
        action: 'apply_audit',
        backup_file: backupFile,
        target_file: CONFIG_FILE,
        audit_file: auditFile,
        form_sn: formSn,
        at: new Date().toISOString()
    })

    // 10. 移动审核文件到 approved 目录(如果是从 pending 来的)
    if (sourceDir === PENDING_DIR) {
        ensureDir(APPROVED_DIR)
        const fileName = path.basename(auditFile)
        const approvedPath = path.join(APPROVED_DIR, fileName)

        // 检查目标是否已存在
        if (fs.existsSync(approvedPath)) {
            console.log("⚠️  approved 目录已存在同名文件,跳过移动")
        } else {
            fs.renameSync(auditFile, approvedPath)
            console.log("📁 审核文件已移动到: " + approvedPath)

            // 删除空的 pending 子目录
            const pendingSubDir = path.dirname(auditFile)
            const remainingFiles = fs.readdirSync(pendingSubDir).filter(f => !f.startsWith('.'))
            if (remainingFiles.length === 0) {
                fs.rmdirSync(pendingSubDir)
                console.log("🗑️  已删除空目录: " + pendingSubDir)
            }
        }
    }

    return { ok: true, formSn, backupFile }
}

function updateConfigFile(newConfigs, options = {}) {
  console.log("\n" + "=".repeat(60))
  console.log("📝 更新配置文件: " + CONFIG_FILE)
  console.log("=".repeat(60))

  const existingContent = fs.readFileSync(CONFIG_FILE, 'utf-8')
  const updateResult = buildConfigUpdateResult(existingContent, newConfigs, options)
  if (!updateResult.ok && updateResult.conflicts.length > 0) {
    console.error("❌ 检测到重复 form_sn: " + updateResult.conflicts.join(', '))
    return { ok: false, reason: 'conflict', conflicts: updateResult.conflicts }
  }

  if (!updateResult.ok) {
    console.error('❌ 无法定位 PLAN_TEMPLATES 插入位置')
    return { ok: false, reason: 'insert_not_found', conflicts: [] }
  }

  if (options.dry_run) {
    console.log("\n🧪 dry-run 变更预览:\n" + updateResult.diff)
    return {
        ok: true,
        dry_run: true,
        diff: updateResult.diff,
        form_sn_list: newConfigs.map(item => item.formSn),
        updated_count: newConfigs.length
    }
  }

  let backupFile = null
  if (fs.existsSync(CONFIG_FILE)) {
    ensureDir(BACKUP_DIR)
    backupFile = path.join(BACKUP_DIR, `plan-templates.backup.${Date.now()}.js`)
    fs.copyFileSync(CONFIG_FILE, backupFile)
    console.log("💾 已备份到: " + backupFile)
  }

  writeFile(CONFIG_FILE, updateResult.updatedContent)
  writeBackupLog({
    action: 'update',
    backup_file: backupFile,
    target_file: CONFIG_FILE,
    form_sn_list: newConfigs.map(item => item.formSn),
    at: new Date().toISOString()
  })
  console.log("✅ 已更新配置文件,新增 " + newConfigs.length + " 个产品")
  return {
      ok: true,
      dry_run: false,
      backup_file: backupFile,
      form_sn_list: newConfigs.map(item => item.formSn),
      updated_count: newConfigs.length
  }
}

/**
 * 处理所有文档
 *
 * @description 支持单产品和多产品文档的批量处理
 */
async function parseAllDocs(docs, options = {}) {
  if (docs.length === 0) {
    console.log('📭 没有待处理的文档')
    return
  }

  const start_time = Date.now()
  console.log("\n" + "=".repeat(60))
  console.log("📚 发现 " + docs.length + " 个待处理文档")
  console.log("=".repeat(60))

  const results = []
  const successResults = []

  for (const doc of docs) {
    const result = await parseSingleFile(doc.fullPath)

    // 处理多产品返回值
    if (result.multiProduct) {
      // 多产品文档
      console.log("\n📦 文档 " + result.file + " 包含 " + result.productCount + " 个产品,成功 " + result.successCount + " 个")

      // 添加文档级结果
      results.push(result)

      // 展开每个成功的产品到 successResults
      if (result.results) {
        result.results.forEach(r => {
          if (r.success && r.code) {
            successResults.push(r)
          }
        })
      }
    } else {
      // 单产品文档
      results.push(result)
      if (result.success && result.code) {
        successResults.push(result)
      }
    }
  }

  // 计算实际产品数量
  const totalProducts = results.reduce((sum, r) => {
    return sum + (r.multiProduct ? r.productCount : 1)
  }, 0)
  const successProducts = successResults.length

  // 汇总
  console.log("\n" + "=".repeat(60))
  console.log("📊 解析结果汇总")
  console.log("=".repeat(60))
  console.log("文档: " + docs.length + " 个")
  console.log("产品: " + totalProducts + " 个(成功: " + successProducts + ", 失败: " + (totalProducts - successProducts) + ")")

  const summary = buildParseSummary(results, Date.now() - start_time)
  console.log("耗时: " + summary.duration_ms + "ms")

  // 显示成功的产品
  if (successResults.length > 0) {
    console.log("\n✅ 成功解析的产品:")
    successResults.forEach(r => {
      const productInfo = r.config?.product_name || r.productName || '未知产品'
      console.log("   - " + r.formSn + ": " + productInfo)
    })
  }

  // 显示失败信息
  const failedResults = results.filter(r => !r.success || (r.multiProduct && r.successCount < r.productCount))
  if (failedResults.length > 0) {
    console.log("\n⚠️ 失败/部分失败:")
    failedResults.forEach(r => {
      if (r.multiProduct) {
        console.log("   - " + r.file + " (" + r.successCount + "/" + r.productCount + " 成功)")
      } else {
        console.log("   - " + r.file + " (" + (r.reason || 'unknown') + ")")
      }
    })
  }

  // 更新配置文件
  let update_result = null
  if (successResults.length > 0) {
    update_result = updateConfigFile(successResults, options)
  } else {
    console.log("\n❌ 没有成功解析的产品,配置文件未更新")
  }
  const audit_record = buildAuditRecord(summary, options, update_result, 'batch')
  writeAuditLog(audit_record)
}

/**
 * CLI 入口
 */
async function main() {
  const args = process.argv.slice(2)
  const docs = getDocsToParse()

  // 检查模式
  const listMode = args.includes('--list')
  const fileMode = args.find(arg => arg.startsWith('--file='))
  const writeMode = args.includes('--write-config')
  const rollbackMode = args.find(arg => arg.startsWith('--rollback='))
  const statusMode = args.includes('--status')
  const applyMode = args.find(arg => arg.startsWith('--apply='))

  // dry-run 逻辑:
  // 1. 如果显式指定 --dry-run,则 dry-run
  // 2. 如果是 apply 模式,默认不 dry-run(除非显式指定)
  // 3. 如果是解析模式,默认 dry-run(除非显式指定 --write-config)
  const explicitDryRun = args.includes('--dry-run')
  const dryRunMode = applyMode ? explicitDryRun : (!writeMode && !explicitDryRun || explicitDryRun)

  // 检查解析器选择
  const parserModeArg = args.find(arg => arg.startsWith('--parser='))
  const parserMode = parserModeArg ? parserModeArg.split('=')[1].toLowerCase() : 'mammoth'

  console.log('\n🚀 文档解析工具 v2.0')
  console.log("   文档目录: " + DOCS_DIR)
  console.log("   配置文件: " + CONFIG_FILE)

  // 显示配置状态
  printConfigStatus()

  if (statusMode) {
    // 只显示状态,不执行解析
    return
  }

  if (rollbackMode) {
    const backupFile = rollbackMode.split('=')[1]
    rollbackConfigFile(backupFile)
  } else if (applyMode) {
    // 从审核文件应用配置
    const auditFileName = applyMode.split('=')[1]
    const applyOptions = { dry_run: dryRunMode }
    applyAuditFile(auditFileName, applyOptions)
  } else if (listMode) {
    // 列出模式
    const docs = getDocsToParse()
    console.log("\n📋 待处理文档列表:")
    if (docs.length === 0) {
      console.log('  (无文档)')
    } else {
      docs.forEach((doc, index) => {
        console.log(" " + (index + 1) + ". " + doc.name + " (" + formatSize(doc.size) + ")")
      })
    }
  } else if (fileMode) {
    // 单文件模式
    const fileName = fileMode.split('=')[1]
    // 更宽松的匹配:支持模糊匹配(移除特殊字符后比较)
    const normalize = (str) => str.toLowerCase().replace(/[\s\-_版]/g, '')
    const normalizedFileName = normalize(fileName)
    const targetDoc = docs.find(d => {
      const normalizedName = normalize(d.name)
      return normalizedName === normalizedFileName || normalizedName.includes(normalizedFileName)
    })

    if (targetDoc) {
      const start_time = Date.now()
      const result = await parseSingleFile(targetDoc.fullPath)
      const summary = buildParseSummary([result], Date.now() - start_time)

      // 计算产品数量
      const productCount = result.multiProduct ? result.productCount : 1
      const successCount = result.multiProduct ? result.successCount : (result.success ? 1 : 0)

      console.log("\n📊 解析结果汇总")
      console.log("文档: 1 个")
      console.log("产品: " + productCount + " 个(成功: " + successCount + ", 失败: " + (productCount - successCount) + ")")
      console.log("耗时: " + summary.duration_ms + "ms")

      // 收集成功的产品配置
      let successConfigs = []
      if (result.multiProduct) {
        // 多产品文档:展开子结果
        if (result.results) {
          successConfigs = result.results.filter(r => r.success && r.code)
        }
      } else if (result.success && result.code) {
        // 单产品文档
        successConfigs = [result]
      }

      // 更新配置文件
      let update_result = null
      if (successConfigs.length > 0) {
        update_result = updateConfigFile(successConfigs, { dry_run: dryRunMode })
      } else {
        console.log("\n❌ 没有成功解析的产品,配置文件未更新")
      }

      const audit_record = buildAuditRecord(summary, { dry_run: dryRunMode }, update_result, 'single')
      writeAuditLog(audit_record)
    } else {
      console.log("❌ 找不到文件: " + fileName)
    }
  } else {
    // 批量处理模式
    await parseAllDocs(docs, { dry_run: dryRunMode })
  }

  console.log('\n✨ 处理完成!')
}

const isDirectRun = import.meta.url === `file://${process.argv[1]}`
if (isDirectRun) {
    main().catch(error => {
        console.error('❌ 执行失败:', error)
        process.exit(1)
    })
}