parse-docs.js 40.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 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
/**
 * 文档解析脚本
 *
 * @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
 */
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'

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

const DOCS_DIR = path.resolve(process.cwd(), 'docs/to-parse')
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 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>} 解析后的配置对象
 */
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

    // 步骤 2: 调用 AI 服务从文档内容中提取配置
    // TODO(human): 集成 AI 服务(OpenAI/Anthropic)
    // 需要配置 API Key 和服务端点
    console.log('📝 AI 配置提取: 待集成 AI 服务')

    // 临时方案:生成基础配置(基于文件名和内容启发式推断)
    const fileName = path.basename(docPath, path.extname(docPath))
    const config = {
      product_name: fileName,
      product_type: inferProductType(fileName, content),
      currency: inferCurrency(content),
      payment_periods: ['整付', '3年', '5年'],
      age_range: { min: 0, max: 75 },
      insurance_period: '终身',
      is_savings: true,
      withdrawal_modes: ['年龄指定金额', '最高固定金额'],
      withdrawal_periods: ['1年', '3年', '5年', '10年'],
      form_schema: { base_fields: [], withdrawal_fields: [], reset_map: {} },
      submit_mapping: {}
    }

    console.log('✅ 解析成功 (启发式推断)')
    console.log(`   产品类型: ${config.product_type}`)
    console.log(`   币种: ${config.currency}`)
    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'
}

/**
 * 解析单个文档
 */
async function parseSingleFile(filePath) {
  const fileName = path.basename(filePath)
  console.log("\n" + "=".repeat(60))
  console.log("📄 处理文件: " + fileName)
  console.log("=".repeat(60))

  // 解析文档
  const config = await parseDocumentWithAI(filePath)

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

  const validation = validateParsedConfig(config)
  if (!validation.valid) {
    console.error("❌ 校验失败: " + fileName)
    validation.errors.forEach(message => {
      console.error(" - " + message)
    })
    return { success: false, file: fileName, reason: 'validation_failed', errors: validation.errors }
  }

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

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

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

  // ✨ 新增:生成待审核文件(不直接写入正式配置)
  const auditFile = await generateAuditFile(fileName, config, code)
  if (auditFile) {
    console.log("\n✅ 已生成待审核文件: " + auditFile)
    console.log("📋 请审核后手动移动到 src/config/plan-templates.js")
    return { success: true, formSn, code, file: fileName, config, auditFile }
  }

  return { success: true, formSn, code, file: fileName, config, auditFile }
}

/**
 * 生成待审核文件
 *
 * @description 生成人类可读的 markdown 审核文件
 * @param {string} fileName - 原始文件名
 * @param {Object} config - 解析的配置对象
 * @param {string} code - 生成的配置代码
 * @returns {Promise<string|null>} 审核文件路径
 */
async function generateAuditFile(fileName, config, code) {
  const AUDIT_DIR = path.resolve(process.cwd(), 'docs/parse-audit/pending')
  ensureDir(AUDIT_DIR)

  const date = new Date().toISOString().split('T')[0]
  const auditFileName = `${date}-${fileName.replace(/\.[^/.]+$/, '')}.md`
  const auditFilePath = path.join(AUDIT_DIR, auditFileName)

  const content = `# ${config.product_name || fileName}

## 解析信息

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

---

## 配置预览

\`\`\`javascript
const config = \\${JSON.stringify(config, null, 2)}
\`\`

---

## 审核检查清单

- [ ] 产品名称是否正确
- [ ] 产品类型是否正确(${config.product_type || '未知'}
- [ ] 币种是否正确(${config.currency || '未知'}
- [ ] age_range 是否合理(${config.age_range?.min || 0} - ${config.age_range?.max || 75}岁)
- [ ] form_schema 字段是否完整
- [ ] submit_mapping 逻辑是否正确

---

## 下一步

1. 审核以上配置是否正确
2. 确核通过后,执行以下操作:

\`\`\`bash
# 1. 移动到 approved 目录
mv docs/parse-audit/pending/${auditFileName} docs/parse-audit/approved/

# 2. 手动添加配置到 src/config/plan-templates.js
# 3. 运行 pnpm lint 检
\`\`

---

## 审核状态

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

## 审核意见

<!-- 审核时请填写 -->

**生成时间**: ${new Date().toLocaleString('zh-CN')}
`

<!-- 审核通过后,请执行以下步骤:-->
1. 将此文件移动到 \`docs/parse-audit/approved/\`
2. 手动将配置添加到 \`src/config/plan-templates.js\`
3. 运行 \`pnpm lint\` �查
`

---

**注意**:
- 请仔细核对配置的每个字段
- 确认产品类型和币种是否符合业务需求
- �查 form_schema 中的字段定义是否完整
`

`

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

/**
 * 生成待审核文件
 *
 * @description 生成人类可读的 markdown 审核文件,保存到 docs/parse-audit/pending/
 * @param {string} fileName - 原始文件名
 * @param {Object} config - 解析的配置对象
 * @param {string} code - 生成的配置代码
 * @returns {Promise<string|null>} 审核文件路径
 */
async function generateAuditFile(fileName, config, code) {
  const AUDIT_DIR = path.resolve(process.cwd(), 'docs/parse-audit/pending')
  ensureDir(AUDIT_DIR)

  const date = new Date().toISOString().split('T')[0]
  const auditFileName = `${date}-${fileName.replace(/\.[^/.]+$/, '')}.md`
  const auditFilePath = path.join(AUDIT_DIR, auditFileName)

  const content = `# ${config.product_name || fileName}

## 解析信息

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

---

## 配置预览

\`\`\`javascript
{
  "product_name": "${config.product_name || ''}",
  "product_type": "${config.product_type || ''}",
  "currency": "${config.currency || ''}",
${Object.entries(config).filter(([k]) =>
!['source_file', 'form_schema', 'submit_mapping'].includes(k)
).map(([k, v]) =>
  `  "${k}": ${JSON.stringify(v, null, 2)}`
).join(',\n  ')}
\`\`\`

---

## 审核检查清单

- [ ] 产品名称是否正确
- [ ] 产品类型是否正确
- [ ] 币种是否正确
- [ ] age_range 是否合理
- [ ] payment_periods / withdrawal_periods 是否完整
- [ ] form_schema 字段是否完整
- [ ] 提取逻辑是否符合需求

---

## 审核状态

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

## 审核意见

\`\`\`

<!-- 审核通过后,请执行以下步骤:

1. 将此文件移动到 docs/parse-audit/approved/
2. 手动将配置添加到 src/config/plan-templates.js
3. 提交变更

-->

  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
    }

    const insertContent = newConfigs.map((item, index) => {
        const code = item.code.trimEnd()
        return index === newConfigs.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: results.length,
        success: 0,
        failed: 0,
        duration_ms,
        success_list: [],
        failed_list: []
    }

    results.forEach(result => {
        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 || []
            })
        }
    })

    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
}

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

/**
 * 处理所有文档
 */
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)
    results.push(result)
    if (result.success) {
      successResults.push(result)
    }
  }

  // 汇总
  console.log("\n" + "=".repeat(60))
  console.log("📊 解析结果汇总")
  console.log("=".repeat(60))
  console.log("总计: " + docs.length + " 个文档")
  console.log("成功: " + successResults.length + " 个")
  console.log("失败: " + (results.length - successResults.length) + " 个")
  const summary = buildParseSummary(results, Date.now() - start_time)
  console.log("耗时: " + summary.duration_ms + "ms")

  // 显示成功的产品
  if (successResults.length > 0) {
    console.log("\n✅ 成功解析的产品:")
    successResults.forEach(r => {
      console.log("   - " + r.formSn + ": " + r.config.product_name)
    })
  }
  if (summary.failed_list.length > 0) {
    console.log("\n⚠️ 失败明细:")
    summary.failed_list.forEach(item => {
      console.log("   - " + item.file + " (" + item.reason + ")")
    })
  }

  // 更新配置文件
  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 dryRunMode = args.includes('--dry-run')
  const rollbackMode = args.find(arg => arg.startsWith('--rollback='))
  const statusMode = args.includes('--status')

  // 检查解析器选择
  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 (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, parserMode)
      const summary = buildParseSummary([result], Date.now() - start_time)
      console.log("\n📊 解析结果汇总")
      console.log("总计: " + summary.total + " 个文档")
      console.log("成功: " + summary.success + " 个")
      console.log("失败: " + summary.failed + " 个")
      console.log("耗时: " + summary.duration_ms + "ms")
      if (result.success) {
        const update_result = updateConfigFile([result], { dry_run: dryRunMode })
        const audit_record = buildAuditRecord(summary, { dry_run: dryRunMode }, update_result, 'single')
        writeAuditLog(audit_record)
      } else {
        const audit_record = buildAuditRecord(summary, { dry_run: dryRunMode }, null, '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)
    })
}