from docx import Document

docx_path = "C:/Users/AlexAdkins/Downloads/terms.docx"
txt_path = "license_test.txt"

def wrap_text(text, indent_text, max_length=85):
    """
    Wrap text to a specified maximum length, preserving indentation.
    """
    wrapped_lines = []
    words = text.split()
    current_line = indent_text
    for word in words:
        if len(current_line) + len(word) + 1 > max_length:
            current_line = str(current_line)
            current_line = current_line.replace(u"\u201C", '"') #curly quotes
            current_line = current_line.replace(u"\u201D", '"') #curly quotes
            current_line = current_line.replace(u"\u2122", '(TM)') # TM symbol
            wrapped_lines.append(current_line)
            current_line = indent_text + word
        else:
            current_line = f"{current_line} {word}" if current_line != indent_text else current_line + word
    current_line = current_line.replace(u"\u201C", '"')
    current_line = current_line.replace(u"\u201D", '"')
    current_line = current_line.replace(u"\u2122", '(TM)') # TM symbol
    # if len(current_line) < 15:
    #     length = len(current_line)
    #     padding = (max_length - len(current_line)) // 2
    #     current_line = ' ' * padding + current_line
    wrapped_lines.append(current_line)
    return wrapped_lines

def docx_to_txt_with_formatting(docx_path, txt_path):
  doc = Document(docx_path)
  with open(txt_path, 'w', encoding='utf-8') as txt_file:
    for paragraph in doc.paragraphs:
      # Simplified indentation calculation (adjust as needed)
      indent = paragraph.paragraph_format.left_indent
      indent_level = 0 if indent is None else int(indent.pt / 36)  # Example conversion
      indent_text = '    ' * indent_level  # 4 spaces per indent level
      
      # Wrap paragraph text to max 100 characters, preserving indentation
      wrapped_text = wrap_text(paragraph.text, indent_text, max_length=100)
      
      # Write the wrapped, indented text to the file
      for line in wrapped_text:
          txt_file.write(line + "\n")

docx_to_txt_with_formatting(docx_path, txt_path)