import fs from 'fs'
import path from 'path'
import { PDFDocument } from 'pdf-lib'

async function main() {
  // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
  const uploads = path.join(process.cwd(), 'public', 'uploads')
  const files = fs.existsSync(uploads) ? fs.readdirSync(uploads).filter(f => f.toLowerCase().endsWith('.pdf')) : []
  if (files.length === 0) { console.log('no pdfs'); return }
  // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
  files.sort((a,b) => {
    // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
    const pathB = path.join(uploads, b)
    // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
    const pathA = path.join(uploads, a)
    return fs.statSync(pathB).mtimeMs - fs.statSync(pathA).mtimeMs
  })
  // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
  const latest = path.join(uploads, files[0])
  console.log('Inspecting', latest)
  const bytes = fs.readFileSync(latest)
  const pdf = await PDFDocument.load(bytes)
  let form
  try { form = pdf.getForm() } catch (e) { form = null }
  if (!form) { console.log('no form'); return }
  const fields = form.getFields()
  const matches = []
  for (const f of fields) {
    const name = f.getName()
    try {
      if (typeof f.getText === 'function') {
        const v = f.getText()
        if (v && (String(v).toLowerCase() === 'aktiv' || String(v).toLowerCase() === 'passiv')) {
          matches.push({ name, value: v })
        }
      } else if (typeof f.isChecked === 'function') {
        const checked = f.isChecked()
        if (checked) {
          // value true -> possibly membership
          matches.push({ name, value: 'checked' })
        }
      }
    } catch (e) {}
  }
  if (matches.length === 0) console.log('no aktiv/passiv values found')
  else console.log('matches:', matches)
}

main().catch(e => { console.error(e); process.exit(1) })
