#!/usr/bin/env python3
"""Fix DOCX XML structure issues"""
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path
import tempfile
import shutil

docx_path = '/sessions/dreamy-great-hypatia/mnt/mdp/Fabric prime/02_Appendix_A_Security_Privacy_Model_Fabric_Primary_v1.docx'

# Read the docx as a zip
with tempfile.TemporaryDirectory() as tmpdir:
    # Extract
    with zipfile.ZipFile(docx_path, 'r') as zip_ref:
        zip_ref.extractall(tmpdir)

    # Read document.xml
    doc_path = Path(tmpdir) / 'word' / 'document.xml'
    with open(doc_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # The issue is likely that the document element is not properly closed
    # Ensure it ends properly
    if not content.strip().endswith('</w:document>'):
        print("Fixing document.xml structure...")
        # Remove any stray characters after the last proper closing tag
        if '</w:document>' in content:
            idx = content.rfind('</w:document>')
            content = content[:idx + len('</w:document>')]

    # Write back
    with open(doc_path, 'w', encoding='utf-8') as f:
        f.write(content)

    # Repack the zip
    with zipfile.ZipFile(docx_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in __import__('os').walk(tmpdir):
            for file in files:
                file_path = Path(root) / file
                arcname = file_path.relative_to(tmpdir)
                zipf.write(file_path, arcname)

print(f"Fixed {docx_path}")
