#!/usr/bin/env python3
"""Add JvG Consultancy branding to all REACH v2.0 deliverables."""

import os
from pathlib import Path
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, nsdecls
from docx.oxml import parse_xml
from pptx import Presentation
from pptx.util import Inches, Pt as PptxPt, Emu as PptxEmu
from pptx.dml.color import RGBColor as PptxRGBColor
from pptx.enum.text import PP_ALIGN
from lxml import etree

LOGO_MED = "/root/projects/jg/assets/branding/jvg-logo-white-medium.png"
LOGO_LRG = "/root/projects/jg/assets/branding/jvg-logo-white-large.png"

DOCX_FILES = [
    "/root/projects/jg/2026-reach-phoenix-metals/deliverables/docx/REACH_Kennisdossier_Phoenix_Metals_D1_v2.0.docx",
    "/root/projects/jg/2026-reach-phoenix-metals/deliverables/docx/REACH_VeiligWerken_HSEQ_Framework_Phoenix_Metals_D2_v2.0.docx",
    "/root/projects/jg/2026-reach-phoenix-metals/deliverables/docx/REACH_VIB_MSDS_Strategie_Phoenix_Metals_D3_v2.0.docx",
    "/root/projects/jg/2026-reach-phoenix-metals/deliverables/docx/REACH_MasterSOP_Phoenix_Metals_D4_v2.0.docx",
    "/root/projects/jg/2026-reach-phoenix-metals/deliverables/docx/REACH_Kennisdossier_Studiemateriaal_Phoenix_Metals_v1.0.docx",
]

PPTX_FILE = "/root/projects/jg/2026-reach-phoenix-metals/deliverables/pptx/REACH_Management_Presentatie_Phoenix_Metals_D5_v2.0.pptx"

results = []


def set_cell_shading(cell, color_hex):
    """Set background color on a table cell."""
    shading = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{color_hex}"/>')
    cell._tc.get_or_add_tcPr().append(shading)


def process_docx(filepath):
    """Add JvG header and footer to a DOCX file."""
    basename = os.path.basename(filepath)
    try:
        doc = Document(filepath)
        sections = doc.sections

        for section in sections:
            # --- HEADER ---
            section.different_first_page_header_footer = False

            header = section.header
            header.is_linked_to_previous = False

            # Clear existing header content
            for p in header.paragraphs:
                p.clear()
            for t in header.tables:
                t._element.getparent().remove(t._element)

            # Build header as a 2-cell table for layout control
            # Use paragraph with run for text, then logo run
            # Actually python-docx header support is limited. Let's use XML approach.
            # We'll create a table in the header
            
            # Add a 1-cell table for the header background
            tbl = header.add_table(rows=1, cols=2, width=Cm(16))
            tbl.autofit = False

            # Left cell: text
            left_cell = tbl.cell(0, 0)
            left_cell.width = Cm(12)
            set_cell_shading(left_cell, "003366")
            p = left_cell.paragraphs[0]
            p.alignment = WD_ALIGN_PARAGRAPH.LEFT
            run = p.add_run("JvG Consultancy | Safety • Governance • Advisory")
            run.font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)
            run.font.size = Pt(9)
            run.font.name = "Calibri"

            # Right cell: logo
            right_cell = tbl.cell(0, 1)
            right_cell.width = Cm(4)
            set_cell_shading(right_cell, "003366")
            p2 = right_cell.paragraphs[0]
            p2.alignment = WD_ALIGN_PARAGRAPH.RIGHT
            run2 = p2.add_run()
            run2.add_picture(LOGO_MED, width=Cm(2.0), height=Cm(1.8))

            # --- FOOTER ---
            footer = section.footer
            footer.is_linked_to_previous = False

            for p in footer.paragraphs:
                p.clear()
            for t in footer.tables:
                t._element.getparent().remove(t._element)

            tbl2 = footer.add_table(rows=1, cols=3, width=Cm(16))
            tbl2.autofit = False

            # Left: confidential
            c1 = tbl2.cell(0, 0)
            c1.width = Cm(6)
            set_cell_shading(c1, "F8F9FA")
            p = c1.paragraphs[0]
            p.alignment = WD_ALIGN_PARAGRAPH.LEFT
            run = p.add_run("JvG Consultancy — Vertrouwelijk")
            run.font.size = Pt(8)
            run.font.color.rgb = RGBColor(0x33, 0x33, 0x33)
            run.font.name = "Calibri"

            # Center: page number
            c2 = tbl2.cell(0, 1)
            c2.width = Cm(4)
            set_cell_shading(c2, "F8F9FA")
            p = c2.paragraphs[0]
            p.alignment = WD_ALIGN_PARAGRAPH.CENTER
            # Insert PAGE field
            run = p.add_run()
            fldChar1 = parse_xml(f'<w:fldChar {nsdecls("w")} w:fldCharType="begin"/>')
            run._r.append(fldChar1)
            run2 = p.add_run()
            instrText = parse_xml(f'<w:instrText {nsdecls("w")} xml:space="preserve"> PAGE </w:instrText>')
            run2._r.append(instrText)
            run3 = p.add_run()
            fldChar2 = parse_xml(f'<w:fldChar {nsdecls("w")} w:fldCharType="end"/>')
            run3._r.append(fldChar2)
            for r in [run, run2, run3]:
                r.font.size = Pt(8)
                r.font.name = "Calibri"

            # Right: Phoenix Metals
            c3 = tbl2.cell(0, 2)
            c3.width = Cm(6)
            set_cell_shading(c3, "F8F9FA")
            p = c3.paragraphs[0]
            p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
            run = p.add_run("Phoenix Metals — REACH Compliance")
            run.font.size = Pt(8)
            run.font.color.rgb = RGBColor(0x33, 0x33, 0x33)
            run.font.name = "Calibri"

            # Remove table borders for cleaner look
            for table in [tbl, tbl2]:
                tbl_xml = table._tbl
                tblPr = tbl_xml.tblPr
                if tblPr is None:
                    tblPr = parse_xml(f'<w:tblPr {nsdecls("w")}/>')
                    tbl_xml.insert(0, tblPr)
                borders = parse_xml(
                    f'<w:tblBorders {nsdecls("w")}>'
                    '  <w:top w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
                    '  <w:left w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
                    '  <w:bottom w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
                    '  <w:right w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
                    '  <w:insideH w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
                    '  <w:insideV w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
                    '</w:tblBorders>'
                )
                # Remove existing borders if any
                existing = tblPr.find(qn('w:tblBorders'))
                if existing is not None:
                    tblPr.remove(existing)
                tblPr.append(borders)

        doc.save(filepath)
        results.append(f"✅ DOCX: {basename} — header & footer added")
    except Exception as e:
        results.append(f"❌ DOCX: {basename} — ERROR: {e}")


def process_pptx(filepath):
    """Add JvG logo and footer to all slides."""
    basename = os.path.basename(filepath)
    try:
        prs = Presentation(filepath)
        slide_width = prs.slide_width
        slide_height = prs.slide_height

        for i, slide in enumerate(prs.slides):
            # Logo position: top-right
            logo_w = Inches(1.5)
            logo_h = Inches(1.35)

            if i == 0:
                # Title slide: larger centered logo
                logo_w = Inches(2.5)
                logo_h = Inches(2.25)
                left = (slide_width - logo_w) // 2
                top = Inches(0.5)
            else:
                left = slide_width - logo_w - Inches(0.3)
                top = Inches(0.2)

            slide.shapes.add_picture(LOGO_LRG, left, top, logo_w, logo_h)

            # Footer text box
            txBox = slide.shapes.add_textbox(Inches(0.3), slide_height - Inches(0.5), slide_width - Inches(0.6), Inches(0.4))
            tf = txBox.text_frame
            tf.word_wrap = True
            p = tf.paragraphs[0]

            # Left-aligned text
            run = p.add_run()
            run.text = "JvG Consultancy | Safety • Governance • Advisory"
            run.font.size = PptxPt(9)
            run.font.color.rgb = PptxRGBColor(0x00, 0x33, 0x66)
            run.font.name = "Calibri"
            p.alignment = PP_ALIGN.LEFT

        prs.save(filepath)
        results.append(f"✅ PPTX: {basename} — logo & footer added to {len(prs.slides)} slides")
    except Exception as e:
        results.append(f"❌ PPTX: {basename} — ERROR: {e}")


if __name__ == "__main__":
    print("=== JvG Consultancy Branding Fix ===\n")

    for f in DOCX_FILES:
        print(f"Processing {os.path.basename(f)}...")
        process_docx(f)

    print(f"\nProcessing {os.path.basename(PPTX_FILE)}...")
    process_pptx(PPTX_FILE)

    print("\n=== Results ===")
    for r in results:
        print(r)

    # Write changelog
    log_path = "/root/projects/jg/2026-reach-phoenix-metals/logs/changelog.md"
    os.makedirs(os.path.dirname(log_path), exist_ok=True)
    with open(log_path, "w") as f:
        f.write("# Changelog — JvG Branding Fix\n\n")
        f.write("**Datum:** 2026-04-16\n")
        f.write("**Actie:** JvG Consultancy branding toegevoegd aan alle REACH v2.0 deliverables\n\n")
        f.write("## DOCX Bestanden (5)\n")
        f.write("- Header: donkerblauw (#003366) achtergrond, tekst + logo\n")
        f.write("- Footer: lichtgrijs (#F8F9FA), vertrouwelijk + paginanummer + Phoenix Metals\n\n")
        f.write("## PPTX Bestand (1)\n")
        f.write("- Logo rechtsboven op elke slide\n")
        f.write("- Footer tekst onderaan elke slide\n\n")
        f.write("## Resultaten\n\n")
        for r in results:
            f.write(f"- {r}\n")

    print(f"\nChangelog geschreven naar {log_path}")
