#!/usr/bin/env python3
"""Merge Part A + Part B into final Kennisdossier with running headers/footers."""

import copy
from docx import Document
from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt, RGBColor

PART_A = "/root/projects/jg/2026-pgs15-phoenix-metals/working/map/doc01_partA.docx"
PART_B = "/root/projects/jg/2026-pgs15-phoenix-metals/working/map/doc01_partB.docx"
OUTPUT = "/root/projects/jg/2026-pgs15-phoenix-metals/deliverables/docx/PGS15_Kennisdossier_PhoenixMetals_v1.0.docx"

# Load documents
docA = Document(PART_A)
docB = Document(PART_B)

# Add page break before appending Part B content
from docx.oxml import OxmlElement
pb = OxmlElement('w:p')
run = OxmlElement('w:r')
br = OxmlElement('w:br')
br.set(qn('w:type'), 'page')
run.append(br)
pb.append(run)
docA.element.body.append(pb)

# Copy all body elements from Part B (skip section properties)
for element in docB.element.body:
    if element.tag != qn('w:sectPr'):
        docA.element.body.append(copy.deepcopy(element))

# Add running headers and footers to ALL sections
def add_header_footer(doc):
    for section in doc.sections:
        header = section.header
        header.is_linked_to_previous = False
        hp = header.paragraphs[0]
        hp.alignment = WD_ALIGN_PARAGRAPH.RIGHT
        run = hp.add_run("JvG Consultancy | PGS-15 Compliance Kennisdossier")
        run.font.size = Pt(9)
        run.font.color.rgb = RGBColor(0x37, 0x41, 0x51)
        run.font.name = 'Calibri'
        
        footer = section.footer
        footer.is_linked_to_previous = False
        fp = footer.paragraphs[0]
        fp.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = fp.add_run("© 2026 JvG Consultancy | HSEQ Divisie | 26 april 2026 | Vertrouwelijk")
        run.font.size = Pt(8)
        run.font.color.rgb = RGBColor(0x37, 0x41, 0x51)
        run.font.name = 'Calibri'

add_header_footer(docA)

# Save
docA.save(OUTPUT)
print(f"✅ Saved to {OUTPUT}")

# Verification
doc = Document(OUTPUT)
word_count = sum(len(p.text.split()) for p in doc.paragraphs)
table_count = len(doc.tables)
heading_count = sum(1 for p in doc.paragraphs if p.style.name.startswith('Heading'))
section_count = len(doc.sections)
headers_present = sum(1 for s in doc.sections if s.header.paragraphs[0].text.strip())
footers_present = sum(1 for s in doc.sections if s.footer.paragraphs[0].text.strip())

print(f"\n=== VERIFICATIE ===")
print(f"Woorden:        {word_count}")
print(f"Tabellen:       {table_count}")
print(f"Headings:       {heading_count}")
print(f"Sections:       {section_count}")
print(f"Headers actief: {headers_present}/{section_count}")
print(f"Footers actief: {footers_present}/{section_count}")
