#!/usr/bin/env python3
"""
JvG Consultancy — Procedure Generator
Procedure: Safe Handling of Mercury — Offshore Decommissioning
Basis: 00_meta_dossier_mercury_audit.md (HSEQ Compliance Audit Koole 003.057)
Structuur: MASTER_STYLEGUIDE §2.2 (7 hoofdstukken) / MASTER_SOP §3.5 Compliance-type
Kwaliteitsniveau: PGS15 (5.000+ woorden, bronverwijzingen [n] bij feitelijke claims)
"""

from docx import Document
from docx.shared import RGBColor, Pt, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

# ------------------------------------------------------------------
# JvG Branding
# ------------------------------------------------------------------
PRIMARY_HEX = "003366"
PRIMARY = RGBColor(0x00, 0x33, 0x66)   # JvG donkerblauw
ACCENT = RGBColor(0x00, 0xA8, 0xE8)    # JvG lichtblauw
DARKGREY = RGBColor(0x1F, 0x29, 0x37)
ZEBRA_HEX = "F8F9FA"
LOGO = "/root/projects/jg/2026-audit-koole-mercury-003057/working/assets/jvg-logo.png"
LOGO_W_CM, LOGO_H_CM = 2.0, 1.8

DOC_CODE = "JvG-HSEQ-PRO-003057"
DOC_DATE = "24 augustus 2026"

# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------

def set_font(run, font_name="Calibri", size=11, bold=False, italic=False, color=None):
    run.font.name = font_name
    run.font.size = Pt(size)
    run.font.bold = bold
    run.font.italic = italic
    run.font.color.rgb = color if color else RGBColor(0, 0, 0)
    rpr = run._element.get_or_add_rPr()
    rfonts = rpr.find(qn("w:rFonts"))
    if rfonts is None:
        rfonts = OxmlElement("w:rFonts")
        rpr.append(rfonts)
    rfonts.set(qn("w:eastAsia"), font_name)


def para(doc, text, size=11, bold=False, italic=False, color=None,
         align=WD_ALIGN_PARAGRAPH.JUSTIFY, space_after=8, space_before=0):
    p = doc.add_paragraph()
    p.alignment = align
    p.paragraph_format.space_after = Pt(space_after)
    p.paragraph_format.space_before = Pt(space_before)
    r = p.add_run(text)
    set_font(r, size=size, bold=bold, italic=italic, color=color)
    return p


def heading(doc, text, level=1):
    """Kop conform JvG-stijl: Calibri, blauw, hiërarchische groottes."""
    sizes = {1: 16, 2: 13, 3: 12}
    p = doc.add_paragraph(style="Heading %d" % level)
    p.paragraph_format.space_before = Pt(14 if level == 1 else 10)
    p.paragraph_format.space_after = Pt(8)
    p.paragraph_format.keep_with_next = True
    r = p.add_run(text)
    set_font(r, size=sizes[level], bold=True, color=PRIMARY if level < 3 else DARKGREY)
    if level == 1:
        pPr = p._element.get_or_add_pPr()
        pBdr = OxmlElement("w:pBdr")
        bottom = OxmlElement("w:bottom")
        bottom.set(qn("w:val"), "single")
        bottom.set(qn("w:sz"), "12")
        bottom.set(qn("w:space"), "2")
        bottom.set(qn("w:color"), PRIMARY_HEX)
        pBdr.append(bottom)
        pPr.append(pBdr)
    return p


def bullet(doc, text, level=0, bold_prefix=None):
    p = doc.add_paragraph(style="List Bullet")
    p.paragraph_format.left_indent = Cm(0.75 + 0.5 * level)
    p.paragraph_format.space_after = Pt(4)
    if bold_prefix:
        set_font(p.add_run(bold_prefix), bold=True)
    set_font(p.add_run(text))
    return p


def step(doc, nr, owner, text):
    """Genummerde procedurestap met eigenaar (Styleguide: genummerde stappen, eigenaren)."""
    p = doc.add_paragraph()
    p.paragraph_format.left_indent = Cm(0.9)
    p.paragraph_format.first_line_indent = Cm(-0.9)
    p.paragraph_format.space_after = Pt(6)
    set_font(p.add_run("Stap %d — " % nr), bold=True, color=PRIMARY)
    set_font(p.add_run("[%s] " % owner), bold=True)
    set_font(p.add_run(text))
    return p


def set_cell_bg(cell, hex_fill):
    tcPr = cell._element.get_or_add_tcPr()
    shd = OxmlElement("w:shd")
    shd.set(qn("w:val"), "clear")
    shd.set(qn("w:fill"), hex_fill)
    tcPr.append(shd)


def make_table(doc, headers, rows, widths=None, font_size=10, zebra=True):
    t = doc.add_table(rows=1 + len(rows), cols=len(headers))
    t.style = "Table Grid"
    t.alignment = WD_TABLE_ALIGNMENT.CENTER
    for j, h in enumerate(headers):
        cell = t.rows[0].cells[j]
        cell.text = ""
        r = cell.paragraphs[0].add_run(h)
        set_font(r, size=font_size, bold=True, color=RGBColor(0xFF, 0xFF, 0xFF))
        set_cell_bg(cell, PRIMARY_HEX)
    for i, row in enumerate(rows):
        for j, val in enumerate(row):
            cell = t.rows[i + 1].cells[j]
            cell.text = ""
            r = cell.paragraphs[0].add_run(str(val))
            set_font(r, size=font_size)
            if zebra and i % 2 == 1:
                set_cell_bg(cell, ZEBRA_HEX)
    if widths:
        for j, w in enumerate(widths):
            for row in t.rows:
                row.cells[j].width = Cm(w)
    spacer = doc.add_paragraph()
    spacer.paragraph_format.space_after = Pt(2)
    return t


def add_page_number_footer(section):
    footer = section.footer
    footer.is_linked_to_previous = False
    p = footer.paragraphs[0]
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    r1 = p.add_run("JvG Consultancy — HSEQ Divisie  |  %s v1.0  |  Safe Handling of Mercury  |  Pagina " % DOC_CODE)
    set_font(r1, size=8, color=DARKGREY)
    r2 = p.add_run()
    set_font(r2, size=8, color=DARKGREY)
    fld_begin = OxmlElement("w:fldChar"); fld_begin.set(qn("w:fldCharType"), "begin")
    instr = OxmlElement("w:instrText"); instr.set(qn("xml:space"), "preserve"); instr.text = " PAGE "
    fld_end = OxmlElement("w:fldChar"); fld_end.set(qn("w:fldCharType"), "end")
    r2._element.append(fld_begin); r2._element.append(instr); r2._element.append(fld_end)


def add_header_logo(section):
    header = section.header
    header.is_linked_to_previous = False
    p = header.paragraphs[0]
    p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    run = p.add_run()
    run.add_picture(LOGO, width=Cm(LOGO_W_CM), height=Cm(LOGO_H_CM))


def add_toc(doc):
    para(doc, "Inhoudsopgave", size=14, bold=True, color=PRIMARY,
         align=WD_ALIGN_PARAGRAPH.LEFT, space_after=6)
    p = doc.add_paragraph()
    fld = OxmlElement("w:fldSimple")
    fld.set(qn("w:instr"), 'TOC \\o "1-2" \\h \\z \\u')
    run_el = OxmlElement("w:r")
    t_el = OxmlElement("w:t")
    t_el.text = "Inhoudsopgave — druk F9 in Microsoft Word om te verversen."
    run_el.append(t_el)
    fld.append(run_el)
    p._element.append(fld)


# ------------------------------------------------------------------
# Document
# ------------------------------------------------------------------
doc = Document()

normal = doc.styles["Normal"]
normal.font.name = "Calibri"
normal.font.size = Pt(11)

section = doc.sections[0]
section.top_margin = Cm(2.2)
section.bottom_margin = Cm(2.0)
section.left_margin = Cm(2.4)
section.right_margin = Cm(2.4)
add_header_logo(section)
add_page_number_footer(section)

# ==================================================================
# TITELPAGINA
# ==================================================================
para(doc, "JvG Consultancy", size=14, bold=True, color=PRIMARY,
     align=WD_ALIGN_PARAGRAPH.CENTER, space_after=2)
para(doc, "Safety • Governance • Advisory", size=10, italic=True, color=DARKGREY,
     align=WD_ALIGN_PARAGRAPH.CENTER, space_after=24)

logo_p = doc.add_paragraph()
logo_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
logo_p.add_run().add_picture(LOGO, width=Cm(4.5), height=Cm(4.04))

para(doc, "PROCEDURE", size=12, bold=True, color=ACCENT,
     align=WD_ALIGN_PARAGRAPH.CENTER, space_before=20, space_after=6)
para(doc, "Safe Handling of Mercury", size=26, bold=True, color=PRIMARY,
     align=WD_ALIGN_PARAGRAPH.CENTER, space_after=4)
para(doc, "Offshore Decommissioning — Small Piece Removal", size=14, color=DARKGREY,
     align=WD_ALIGN_PARAGRAPH.CENTER, space_after=20)

make_table(doc,
    ["Gegeven", "Waarde"],
    [
        ["Project", "2026-audit-koole-mercury-003057"],
        ["Opdrachtgever", "Wintershall (offshore olie & gas, Nederland)"],
        ["Uitvoerende aannemer", "Koole"],
        ["Activiteit", "Decommissioning offshore platform — small piece removal"],
        ["Locatie", "Offshore platform, Nederlandse sector Noordzee"],
        ["Jurisdictie", "Nederland"],
        ["Referentieprocedure", "Koole procedure 003.057 Safe Handling of Mercury Rev 1"],
        ["Documentcode", DOC_CODE],
        ["Versie / Status", "1.0 — Final"],
        ["Datum", DOC_DATE],
        ["Opsteller", "Technical Writer (HQ_04), JvG Consultancy — HSEQ Divisie"],
        ["Goedkeuring", "Kas — Director of Operations, JvG Consultancy"],
    ],
    widths=[5.0, 11.5], font_size=10)

para(doc, "Dit document is opgesteld naar aanleiding van de document-gebaseerde HSEQ compliance "
          "audit van de Koole-procedure 003.057. Alle feitelijke inhoud is herleidbaar naar de "
          "referenties in Bijlage D en het auditdossier 2026-audit-koole-mercury-003057.",
     size=9, italic=True, color=DARKGREY, align=WD_ALIGN_PARAGRAPH.CENTER, space_before=10)

doc.add_page_break()

# ==================================================================
# INHOUDSOPGAVE
# ==================================================================
add_toc(doc)
doc.add_page_break()
