#!/usr/bin/env python3
"""Batch fix Element 4 documents: add logo, footer, update header version."""

import os, shutil
from docx import Document
from docx.shared import Cm, Pt, RGBColor, Emu
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn

SRC_DIR = "/root/projects/jg/2026-PM-VBS-Element4/deliverables/docx"
LOGO_PATH = "/root/projects/jg/assets/branding/jvg-logo-white-medium.png"
FOOTER_TEXT = "JvG Consultancy | Safety • Governance • Advisory | © 2026"

fixes = {
    "PM_VBS04_02_Noodprocedures_Scenario's_v1.0.docx": {"logo": True, "footer": True, "header_version": True},
    "PM_VBS04_03_BHV_Organisatie_v1.0.docx":          {"logo": False, "footer": False, "header_version": True},
    "PM_VBS04_05_Crisiscommunicatie_v1.0.docx":        {"logo": False, "footer": False, "header_version": True},
    "PM_VBS04_06_Noodinspectie_Herstel_v1.0.docx":     {"logo": False, "footer": False, "header_version": True},
    "PM_VBS04_07_Oefenprogramma_v1.0.docx":            {"logo": False, "footer": False, "header_version": True},
    "PM_VBS04_08_Formulierenpakket_v1.0.docx":          {"logo": False, "footer": True, "header_version": False},
}

def add_footer(section):
    """Add centered footer with JvG branding to a section."""
    footer = section.footer
    footer.is_linked_to_previous = False
    # Clear existing
    for p in footer.paragraphs:
        p.clear()
    if not footer.paragraphs:
        footer.add_paragraph()
    p = footer.paragraphs[0]
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run(FOOTER_TEXT)
    run.font.name = "Calibri"
    run.font.size = Pt(9)
    run.font.color.rgb = RGBColor(0x66, 0x66, 0x66)

def add_logo_to_header(section):
    """Add logo image to header paragraph."""
    header = section.header
    header.is_linked_to_previous = False
    if not header.paragraphs:
        header.add_paragraph()
    p = header.paragraphs[0]
    run = p.add_run()
    run.add_picture(LOGO_PATH, width=Cm(2.0), height=Cm(1.8))

def update_header_version(doc, filename):
    """Replace v1.0 with v1.1 in document header table/paragraphs."""
    # Search header paragraphs and tables for version references
    for section in doc.sections:
        header = section.header
        # Check tables
        for table in header.tables:
            for row in table.rows:
                for cell in row.cells:
                    for p in cell.paragraphs:
                        for run in p.runs:
                            if "v1.0" in run.text:
                                run.text = run.text.replace("v1.0", "v1.1")
        # Check paragraphs
        for p in header.paragraphs:
            for run in p.runs:
                if "v1.0" in run.text:
                    run.text = run.text.replace("v1.0", "v1.1")

def main():
    results = []
    for filename, fix in fixes.items():
        src = os.path.join(SRC_DIR, filename)
        if not os.path.exists(src):
            results.append(f"❌ {filename} — NOT FOUND")
            continue
        
        doc = Document(src)
        
        if fix["header_version"]:
            update_header_version(doc, filename)
        
        for section in doc.sections:
            if fix["logo"]:
                add_logo_to_header(section)
            if fix["footer"]:
                add_footer(section)
        
        new_name = filename.replace("_v1.0", "_v1.1")
        out_path = os.path.join(SRC_DIR, new_name)
        doc.save(out_path)
        results.append(f"✅ {new_name} (logo={fix['logo']}, footer={fix['footer']}, hdr={fix['header_version']})")
    
    print("\n".join(results))

if __name__ == "__main__":
    main()
