import fs from 'fs'
import path from 'path'
import os from 'os'

const x = fs.readFileSync(path.join(os.tmpdir(), 'gis-doc-raw.xml'), 'utf8')

function decodeEntities(s) {
  return s
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"')
    .replace(/&amp;/g, '&')
}

function stripXml(chunk) {
  return decodeEntities(chunk)
    .replace(/<w:tab[^>]*\/>/g, '\t')
    .replace(/<\/w:p>/g, '\n')
    .replace(/<[^>]+>/g, '')
    .replace(/\n{3,}/g, '\n\n')
    .trim()
}

// Collect paragraphs that look like doc body (skip TOC hyperlinks)
const paras = []
for (const m of x.matchAll(/<w:p[\s\S]*?<\/w:p>/g)) {
  const t = stripXml(m[0])
  if (!t || t.length < 4) continue
  if (t.includes('PAGEREF') || t.includes('HYPERLINK \\l')) continue
  if (t.startsWith('TOC ')) continue
  paras.push(t)
}

const out = []
const keywords = /GIS|cmmap|Map|token|密钥|Marker|GeoJSON|图层|地图|script|container|accessToken|NavigationControl|MouseTool|路线|POI/i
let inSection = false
for (let i = 0; i < paras.length; i++) {
  const p = paras[i]
  if (/^2[\.\s]/.test(p) || /^[0-9]+\s/.test(p) || keywords.test(p)) {
    inSection = true
  }
  if (inSection && keywords.test(p)) {
    out.push(p)
    // include next few lines if code-like
    for (let j = 1; j <= 3 && i + j < paras.length; j++) {
      const n = paras[i + j]
      if (n.includes('{') || n.includes('cmmap') || n.includes('map.') || n.includes('<')) {
        out.push(n)
      }
    }
  }
}

const unique = [...new Set(out)]
const target = path.resolve('doc/大屏/集中化GIS系统JSAPI接口文档-提取.txt')
fs.writeFileSync(target, unique.join('\n\n'), 'utf8')
console.log('written', target, 'lines', unique.length)

// Also dump section 2.x headings
const headings = paras.filter((p) => /^[0-9]+(\.[0-9]+)*\s/.test(p) && p.length < 80)
fs.writeFileSync(path.resolve('doc/大屏/集中化GIS系统JSAPI-目录.txt'), headings.join('\n'), 'utf8')
console.log('headings', headings.length)
