#!/usr/bin/env python3
"""Batch fix: footer + documentheader for all 12 Element 1 documents."""

from docx import Document
from docx.shared import Pt, Cm, Inches, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml.ns import qn, nsdecls
from docx.oxml import parse_xml
import os, re, copy

SRC = "/root/projects/jg/2026-PM-VBS-Element1/archive/batch-fix-pre"
DST = "/root/projects/jg/2026-PM-VBS-Element1/deliverables"
LOGO = "/root/projects/jg/assets/branding/jvg-logo-white-medium.png"

FOOTER_TEXT = "JvG Consultancy | Safety • Governance • Advisory | © 2026"

# Mapping: (source file, output file, doc_type)
DOCS = [
    ("PM_VBS01_01_PBZO_Beleidsdocument_v1.2.docx", "PM_VBS01_01_PBZO_Beleidsdocument_v1.3.docx", "Beleidsdocument"),
    ("PM_VBS01_02_Functieprofielen_Veiligheid_v1.1.docx", "PM_VBS01_02_Functieprofielen_Veiligheid_v1.2.docx", "Functieprofielen"),
    ("PM_VBS01_03_Organigram_Veiligheid_v1.1.docx", "PM_VBS01_03_Organigram_Veiligheid_v1.2.docx", "Organigram"),
    ("PM_VBS01_04_Training_Matrix_v1.1.docx", "PM_VBS01_04_Training_Matrix_v1.2.docx", "Training Matrix"),
    ("PM_VBS01_05_Inwerkprogramma_v1.1.docx", "PM_VBS01_05_Inwerkprogramma_v1.2.docx", "Inwerkprogramma"),
    ("PM_VBS01_06_Toolbox_Meeting_Procedure_v1.0.docx", "PM_VBS01_06_Toolbox_Meeting_Procedure_v1.1.docx", "Procedure"),
    ("PM_VBS01_07_Competentie_Assessment_v1.0.docx", "PM_VBS01_07_Competentie_Assessment_v1.1.docx", "Assessment Formulier"),
    ("PM_VBS01_08_BASIS_Training_Programma_v1.0.docx", "PM_VBS01_08_BASIS_Training_Programma_v1.1.docx", "Training Programma"),
    ("PM_VBS01_09_SPECIFIEKE_Training_Programma_v1.0.docx", "PM_VBS01_09_SPECIFIEKE_Training_Programma_v1.1.docx", "Training Programma"),
    ("PM_VBS01_10_Procedure_Onderaannemers_v1.0.docx", "PM_VBS01_10_Procedure_Onderaannemers_v1.1.docx", "Procedure"),
    ("PM_VBS01_11_Veiligheidsprestatie_Indicatoren_v1.0.docx", "PM_VBS01_11_Veiligheidsprestatie_Indicatoren_v1.1.docx", "KPI Document"),
    ("PM_VBS01_12_Communicatie_Meldingsprocedure_v1.0.docx", "PM_VBS01_12_Communicatie_Meldingsprocedure_v1.1.docx", "Procedure"),
]

def get_version(outfname):
    m = re.search(r'_v(\d+\.\d+)', outfname)
    return m.group(1) if m else "1.0"

def extract_author(doc):
    """Try to find existing author from document properties or first tables."""
    # Check document properties
    core = doc.core_properties
    if core.author:
        return core.author
    return "JvG Consultancy"

def extract_date(doc):
    """Try to find date in existing header table or use default."""
    core = doc.core_properties
    if core.created:
        return core.created.strftime("%Y-%m-%d")
    return "2026-04-28"

def has_documentheader(doc):
    """Check if documentheader table already exists."""
    for t in doc.tables:
        text = ""
        for row in t.rows:
            for cell in row.cells:
                text += cell.text.lower()
        if "project" in text and "versie" in text:
            return True
    return False

def add_documentheader(doc, doc_type, version, author, date):
    """Insert documentheader table at the beginning of the document."""
    # Find insertion point - after any existing title, before main content
    # We'll insert after the first paragraph or at position 1
    body = doc.element.body
    
    # Create header table
    table = doc.add_table(rows=6, cols=2)
    table.style = 'Table Grid'
    table.alignment = WD_TABLE_ALIGNMENT.LEFT
    
    data = [
        ("Project", "2026-PM-VBS-Element1"),
        ("Type", doc_type),
        ("Auteur", author),
        ("Versie", version),
        ("Datum", date),
        ("Status", "Final"),
    ]
    
    for i, (label, value) in enumerate(data):
        cell_l = table.cell(i, 0)
        cell_r = table.cell(i, 1)
        cell_l.text = label
        cell_r.text = value
        # Style
        for cell in [cell_l, cell_r]:
            for p in cell.paragraphs:
                p.style = doc.styles['Normal']
                for run in p.runs:
                    run.font.name = 'Calibri'
                    run.font.size = Pt(10)
        # Bold label
        for run in cell_l.paragraphs[0].runs:
            run.bold = True
        # Background for label column
        shading = parse_xml(f'<w:shd {nsdecls("w")} w:fill="003366"/>')
        cell_l._tc.get_or_add_tcPr().append(shading)
        for run in cell_l.paragraphs[0].runs:
            run.font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)
    
    # Move table to just after the first element (title)
    # Find first paragraph in body and insert table after it
    first_p = body.find(qn('w:p'))
    if first_p is not None:
        tbl_elem = table._tbl
        body.remove(tbl_elem)
        first_p.addnext(tbl_elem)
    # Add a blank paragraph after the table
    spacer = doc.add_paragraph()
    spacer_elem = spacer._p
    body.remove(spacer_elem)
    table._tbl.addnext(spacer_elem)

def fix_footers(doc):
    """Add footer to all sections."""
    for section in doc.sections:
        footer = section.footer
        footer.is_linked_to_previous = False
        
        # Clear existing footer content
        for p in footer.paragraphs:
            p.clear()
        
        if not footer.paragraphs:
            p = footer.add_paragraph()
        else:
            p = footer.paragraphs[0]
        
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = p.add_run(FOOTER_TEXT)
        run.font.name = 'Calibri'
        run.font.size = Pt(10)
        run.font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)
        
        # Add dark background to footer paragraph
        pPr = p._p.get_or_add_pPr()
        shading = parse_xml(f'<w:shd {nsdecls("w")} w:val="clear" w:color="auto" w:fill="374151"/>')
        pPr.append(shading)

def process_file(src_name, dst_name, doc_type):
    src_path = os.path.join(SRC, src_name)
    dst_path = os.path.join(DST, dst_name)
    version = get_version(dst_name)
    
    print(f"Processing: {src_name} → {dst_name}")
    
    doc = Document(src_path)
    author = extract_author(doc)
    date = extract_date(doc)
    
    # Fix 1: Footer
    fix_footers(doc)
    
    # Fix 2: Documentheader (only if not present)
    if not has_documentheader(doc):
        add_documentheader(doc, doc_type, version, author, date)
    else:
        print(f"  → Documentheader already present, skipping")
    
    doc.save(dst_path)
    print(f"  ✓ Saved: {dst_path}")

if __name__ == "__main__":
    os.makedirs(DST, exist_ok=True)
    for src_name, dst_name, doc_type in DOCS:
        process_file(src_name, dst_name, doc_type)
    print("\n✅ Batch fix complete: all 12 documents processed.")
