import os
import pypandoc
from docx import Document
from docx.oxml import parse_xml, OxmlElement
from docx.oxml.ns import qn
from docx.shared import Pt, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
import sys



html_file = "ocr.html"
output_file = "ocr.docx"

if not os.path.exists(html_file):
    raise FileNotFoundError("❌ HTML file not found.")

def set_table_borders(table):
    tbl = table._tbl
    tblPr = tbl.tblPr
    borders = OxmlElement('w:tblBorders')
    attrs = {
        qn('w:val'): 'single',
        qn('w:sz'): '8',
        qn('w:space'): '0',
        qn('w:color'): '000000'
    }
    for name in ['top', 'left', 'bottom', 'right', 'insideH', 'insideV']:
        border = OxmlElement(f'w:{name}')
        for k, v in attrs.items():
            border.set(k, v)
        borders.append(border)
    tblPr.append(borders)

def get_a4_center_watermark(text="CONFIDENTIAL"):
    shape_width = 400
    shape_height = 100
    left_pos = (595.3 - shape_width) / 2
    top_pos = (841.9 - shape_height) / 2
    return f"""
    <w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
         xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
         xmlns:v="urn:schemas-microsoft-com:vml">
      <w:r>
        <w:pict>
          <v:shape id="Watermark"
                   type="#_x0000_t136"
                   style="position:absolute;
                          width:{shape_width}pt;
                          height:{shape_height}pt;
                          left:{left_pos}pt;
                          top:{top_pos}pt;
                          rotation:315;
                          z-index:-251654144;
                          visibility:visible;
                          mso-wrap-style:square"
                   fillcolor="#d0d0d0" stroked="f">
            <v:textpath style="font-family:&quot;Calibri&quot;;font-size:48pt" on="t" string="{text}"/>
          </v:shape>
        </w:pict>
      </w:r>
    </w:p>
    """

def add_image_to_header_footer(header_or_footer, image_path, width=Inches(6.5)):
    paragraph = header_or_footer.paragraphs[0] if header_or_footer.paragraphs else header_or_footer.add_paragraph()
    run = paragraph.add_run()
    run.add_picture(image_path, width=width)
    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

temp_docx = "converted.docx"
pypandoc.convert_file(html_file, 'docx', outputfile=temp_docx)

doc = Document(temp_docx)

[set_table_borders(t) for t in doc.tables]

wm_xml = parse_xml(get_a4_center_watermark("GUILAW.COM"))

header_image_path = "/home/guilaw/public_html/wp-content/uploads/2025/04/guilaw_doc.jpg"
footer_image_path = "/home/guilaw/public_html/wp-content/uploads/2025/04/guilaw_doc.jpg"

for section in doc.sections:
    header = section.header
    header._element.insert(0, wm_xml)
    add_image_to_header_footer(header, header_image_path)
    para = header.paragraphs[0] if header.paragraphs else header.add_paragraph()
    run = para.add_run("")
    run.bold = True
    run.font.size = Pt(12)
    para.alignment = WD_ALIGN_PARAGRAPH.RIGHT

    footer = section.footer
    add_image_to_header_footer(footer, footer_image_path)
    f_para = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
    f_run = f_para.add_run("")
    f_run.font.size = Pt(10)
    f_para.alignment = WD_ALIGN_PARAGRAPH.CENTER

doc.save(output_file)

print(output_file)
os.remove(temp_docx)
