#!/usr/bin/env python3
"""Add JvG Consultancy branding to all PGS-15 deliverables."""

import os
import re
import base64
from datetime import datetime, timezone

from docx import Document
from docx.shared import Cm, Pt, RGBColor, Inches, Emu
from docx.enum.text import WD_ALIGN_PARAGRAPH
# WD_HEADER_FOOTER_LINK not needed
from docx.oxml.ns import qn, nsdecls
from docx.oxml import parse_xml
from pptx import Presentation
from pptx.util import Inches as PptxInches, Pt as PptxPt, Emu as PptxEmu
from pptx.dml.color import RGBColor as PptxRGBColor
from pptx.enum.text import PP_ALIGN

# --- Paths ---
LOGO_MEDIUM = "/root/projects/jg/assets/branding/jvg-logo-white-medium.png"
LOGO_B64_FILE = "/root/projects/jg/assets/branding/logo-white-base64.txt"
BASE = "/root/projects/jg/2026-pgs15-phoenix-metals/deliverables"

DOCX_FILES = [
    f"{BASE}/docx/PGS15_Kennisdossier_Phoenix_Metals_D1_v1.0.docx",
    f"{BASE}/docx/PGS15_Veilig_Werken_HSEQ_Phoenix_Metals_D2_v1.0.docx",
    f"{BASE}/docx/PGS15_Veiligheidsinfo_Documentatie_Phoenix_Metals_D3_v1.0.docx",
    f"{BASE}/docx/PGS15_Master_SOP_Opslagveiligheid_Phoenix_Metals_D4_v1.0.docx",
]

PPTX_FILE = f"{BASE}/pptx/PGS15_Management_Presentatie_Phoenix_Metals_D5_v1.0.pptx"

HTML_FILES = [
    f"{BASE}/html/PGS15_Opslagveiligheid_eLearning_v1.0.html",
    f"{BASE}/html/PGS15_Opslagveiligheid_Quiz_v1.0.html",
]

BRANDING_TEXT = "JvG Consultancy | Safety • Governance • Advisory"
FOOTER_LEFT = "JvG Consultancy — Vertrouwelijk"
FOOTER_RIGHT = "Phoenix Metals — PGS-15 Opslagveiligheid"

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

def add_docx_branding(filepath):
    print(f"  Processing DOCX: {os.path.basename(filepath)}")
    doc = Document(filepath)

    for section in doc.sections:
        # --- HEADER ---
        # Clear existing header paragraphs
        header = section.header
        for p in header.paragraphs:
            p.clear()

        # Use a table for layout: left text | right logo
        table = header.add_table(rows=1, cols=2, width=doc.sections[0].page_width - doc.sections[0].left_margin - doc.sections[0].right_margin)
        table.autofit = True

        # Left cell: branding text
        left_cell = table.cell(0, 0)
        left_cell.width = Cm(14)
        set_cell_shading(left_cell, "003366")
        p = left_cell.paragraphs[0]
        p.alignment = WD_ALIGN_PARAGRAPH.LEFT
        run = p.add_run(BRANDING_TEXT)
        run.font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)
        run.font.size = Pt(9)

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

        # Set table borders to none
        tbl = table._tbl
        tblPr = tbl.tblPr if tbl.tblPr is not None else parse_xml(f'<w:tblPr {nsdecls("w")}/>')
        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>'
        )
        tblPr.append(borders)

        # --- FOOTER ---
        footer = section.footer
        for p in footer.paragraphs:
            p.clear()

        ftable = footer.add_table(rows=1, cols=3, width=doc.sections[0].page_width - doc.sections[0].left_margin - doc.sections[0].right_margin)
        ftable.autofit = True

        # Left: confidential
        fl = ftable.cell(0, 0)
        set_cell_shading(fl, "F8F9FA")
        p = fl.paragraphs[0]
        p.alignment = WD_ALIGN_PARAGRAPH.LEFT
        r = p.add_run(FOOTER_LEFT)
        r.font.size = Pt(8)

        # Center: page number
        fc = ftable.cell(0, 1)
        set_cell_shading(fc, "F8F9FA")
        p = fc.paragraphs[0]
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        # Page number 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)

        # Right: project info
        fr = ftable.cell(0, 2)
        set_cell_shading(fr, "F8F9FA")
        p = fr.paragraphs[0]
        p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
        r = p.add_run(FOOTER_RIGHT)
        r.font.size = Pt(8)

        # Remove borders on footer table too
        ftbl = ftable._tbl
        ftblPr = ftbl.tblPr if ftbl.tblPr is not None else parse_xml(f'<w:tblPr {nsdecls("w")}/>')
        ftblPr.append(borders)  # reuse same borders element — actually need fresh
        # Re-append fresh borders
        fborders = 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>'
        )
        ftblPr.append(fborders)

    doc.save(filepath)
    print(f"    ✓ Saved: {filepath}")

def add_pptx_branding(filepath):
    print(f"  Processing PPTX: {os.path.basename(filepath)}")
    prs = Presentation(filepath)

    for i, slide in enumerate(prs.slides):
        # Add logo top-right
        slide.shapes.add_picture(
            LOGO_MEDIUM,
            left=prs.slide_width - PptxInches(1.8),
            top=PptxInches(0.15),
            width=PptxInches(1.5),
            height=PptxInches(1.35),
        )

        # Add footer text box
        txBox = slide.shapes.add_textbox(
            left=PptxInches(0.3),
            top=prs.slide_height - PptxInches(0.5),
            width=prs.slide_width - PptxInches(0.6),
            height=PptxInches(0.4),
        )
        tf = txBox.text_frame
        tf.word_wrap = True

        # Left-aligned branding text
        p = tf.paragraphs[0]
        p.alignment = PP_ALIGN.LEFT
        r = p.add_run()
        r.text = BRANDING_TEXT
        r.font.size = PptxPt(8)
        r.font.color.rgb = PptxRGBColor(0x66, 0x66, 0x66)

        # Right-aligned page number (use a separate textbox)
        txBox2 = slide.shapes.add_textbox(
            left=prs.slide_width - PptxInches(1.5),
            top=prs.slide_height - PptxInches(0.5),
            width=PptxInches(1.2),
            height=PptxInches(0.4),
        )
        tf2 = txBox2.text_frame
        p2 = tf2.paragraphs[0]
        p2.alignment = PP_ALIGN.RIGHT
        r2 = p2.add_run()
        r2.text = str(i + 1)
        r2.font.size = PptxPt(8)
        r2.font.color.rgb = PptxRGBColor(0x66, 0x66, 0x66)

    prs.save(filepath)
    print(f"    ✓ Saved: {filepath}")

def add_html_branding(filepath, logo_b64):
    print(f"  Processing HTML: {os.path.basename(filepath)}")
    with open(filepath, 'r', encoding='utf-8') as f:
        content = f.read()

    header_html = f'''<div style="background-color:#003366;padding:8px 16px;display:flex;align-items:center;justify-content:space-between;">
  <img src="data:image/png;base64,{logo_b64}" alt="JvG Consultancy" style="height:28px;">
  <span style="color:#ffffff;font-size:13px;font-family:Arial,sans-serif;">{BRANDING_TEXT}</span>
</div>'''

    # Insert after <body> or <body ...>
    if '<body' in content:
        content = re.sub(r'(<body[^>]*>)', r'\1\n' + header_html, content, count=1)
    else:
        # Fallback: insert at start
        content = header_html + '\n' + content

    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(content)
    print(f"    ✓ Saved: {filepath}")

def main():
    print("=" * 60)
    print("JvG Consultancy Branding — PGS-15 Deliverables")
    print("=" * 60)

    # Load base64 logo for HTML
    with open(LOGO_B64_FILE, 'r') as f:
        logo_b64 = f.read().strip()

    # DOCX
    print("\n📄 DOCX files (4):")
    for fp in DOCX_FILES:
        add_docx_branding(fp)

    # PPTX
    print("\n📊 PPTX file (1):")
    add_pptx_branding(PPTX_FILE)

    # HTML
    print("\n🌐 HTML files (2):")
    for fp in HTML_FILES:
        add_html_branding(fp, logo_b64)

    # Changelog
    ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    changelog = f"""# Changelog — PGS-15 Branding Fix

## [{ts}] Branding toegevoegd aan alle deliverables

- **DOCX (4):** Header (logo + branding tekst, bg #003366) + Footer (paginanummer, vertrouwelijk, projectnaam, bg #F8F9FA)
- **PPTX (1):** Logo rechtsboven op alle slides + footer met branding tekst en paginanummer
- **HTML (2):** Header balk met logo en branding tekst (bg #003366)

Script: `working/branding_fix.py`
"""
    logpath = "/root/projects/jg/2026-pgs15-phoenix-metals/logs/changelog.md"
    os.makedirs(os.path.dirname(logpath), exist_ok=True)
    with open(logpath, 'w') as f:
        f.write(changelog)
    print(f"\n📝 Changelog: {logpath}")
    print("\n✅ Done!")

if __name__ == "__main__":
    main()
