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

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

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']

// AI 解析服务选择(通过 skill 调用)
const AI_SERVICE = 'openai' // 'openai' | 'anthropic' | 'openrouter'

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

/**
 * 调用 AI 服务解析文档
 *
 * 这里使用 skill 工具调用实际的 AI 解析服务
 * 可以是:file-url-to-pdf + openai/anthropic skill
 */
async function parseDocumentWithAI(docPath) {
  console.log(`\n🤖 正在解析: ${path.basename(docPath)}`)

  try {
    const extract_result = await extractDocumentText(docPath)

    if (extract_result.warnings.length > 0) {
      extract_result.warnings.forEach(message => {
        console.log(`⚠️  抽取警告: ${message}`)
      })
    }

    if (!extract_result.text || !extract_result.text.trim()) {
      console.error(`❌ 文本抽取失败 (${docPath})`)
      return null
    }

    const content = extract_result.text

    // 模拟解析:从文档内容中提取配置
    // 实际使用时可以调用 AI 服务
    const mockConfig = {
      product_name: path.basename(docPath, path.extname(docPath)),
      product_type: 'savings',
      currency: 'USD',
      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('✅ 解析成功')
    return mockConfig
  } catch (error) {
    console.error(`❌ 解析失败 (${docPath}):`, error.message)
    return null
  }
}

/**
 * 解析单个文档
 */
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)

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

/**
 * 更新配置文件
 * @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='))

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

  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 targetDoc = docs.find(d => d.name === fileName || d.name.includes(fileName))

    if (targetDoc) {
      const start_time = Date.now()
      const result = await parseSingleFile(targetDoc.fullPath)
      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)
    })
}