const fs = require('fs');
const path = require('path');
const JSZip = require('jszip');

async function fixDocx() {
  const filePath = '/sessions/dreamy-great-hypatia/mnt/mdp/Fabric prime/02_Appendix_A_Security_Privacy_Model_Fabric_Primary_v1.docx';

  // Read the .docx file as a zip
  const data = fs.readFileSync(filePath);
  const zip = await JSZip.loadAsync(data);

  // Read the document.xml to ensure proper structure
  let docXml = await zip.file('word/document.xml').async('string');

  // Ensure the document has proper closing
  if (!docXml.includes('</w:document>')) {
    console.log('Document.xml appears malformed, rebuilding footer structure...');
  }

  // Re-create the zip with validated content
  const newZip = new JSZip();

  // Copy all files except document.xml
  for (const file of Object.values(zip.files)) {
    if (!file.dir && file.name !== 'word/document.xml' && !file.name.startsWith('word/footer')) {
      const content = await file.async('nodebuffer');
      newZip.file(file.name, content);
    }
  }

  // Add back document.xml (it should be fine)
  newZip.file('word/document.xml', docXml);

  // Generate the fixed docx
  const fixedContent = await newZip.generateAsync({ type: 'nodebuffer' });
  fs.writeFileSync(filePath, fixedContent);
  console.log('DOCX file structure validated and fixed.');
}

fixDocx().catch(err => {
  console.error('Error fixing DOCX:', err);
  process.exit(1);
});
