#!/usr/bin/env python3
"""Generate VBS Element 4 Document #6: Noodinspectie & Herstel Protocol"""

from docx import Document
from docx.shared import Cm, Inches, Pt, RGBColor, Emu
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.section import WD_ORIENT
from docx.oxml.ns import qn, nsdecls
from docx.oxml import parse_xml
import os, datetime

OUT = "/root/projects/jg/2026-PM-VBS-Element4/deliverables/docx"
os.makedirs(OUT, exist_ok=True)

doc = Document()

# ── Styles ──
style = doc.styles['Normal']
style.font.name = 'Calibri'
style.font.size = Pt(11)
style.font.color.rgb = RGBColor(0x1F, 0x29, 0x37)
style.paragraph_format.space_after = Pt(4)

PRIMARY = RGBColor(0x00, 0x33, 0x66)
TEXT = RGBColor(0x1F, 0x29, 0x37)
WHITE = RGBColor(0xFF, 0xFF, 0xFF)
GREY_BG = "D9E2F3"

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

def add_heading_styled(text, level=1):
    h = doc.add_heading(text, level=level)
    for run in h.runs:
        run.font.color.rgb = PRIMARY
        run.font.name = 'Calibri'
    return h

def add_table_with_header(headers, rows):
    table = doc.add_table(rows=1+len(rows), cols=len(headers))
    table.style = 'Table Grid'
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    # Header row
    for i, h in enumerate(headers):
        cell = table.rows[0].cells[i]
        cell.text = h
        for p in cell.paragraphs:
            p.alignment = WD_ALIGN_PARAGRAPH.CENTER
            for r in p.runs:
                r.bold = True
                r.font.color.rgb = WHITE
                r.font.size = Pt(10)
        set_cell_shading(cell, "003366")
    # Data rows
    for ri, row in enumerate(rows):
        for ci, val in enumerate(row):
            cell = table.rows[ri+1].cells[ci]
            cell.text = val
            for p in cell.paragraphs:
                for r in p.runs:
                    r.font.size = Pt(10)
            if ri % 2 == 1:
                set_cell_shading(cell, GREY_BG)
    return table

def add_footer(section):
    footer = section.footer
    footer.is_linked_to_previous = False
    p = footer.paragraphs[0]
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run("JvG Consultancy | Safety • Governance • Advisory | © 2026")
    run.font.size = Pt(8)
    run.font.color.rgb = RGBColor(0x80, 0x80, 0x80)
    run.font.name = 'Calibri'

def add_logo_paragraph():
    logo_path = "/root/projects/jg/assets/branding/jvg-logo-white-medium.png"
    if os.path.exists(logo_path):
        p = doc.add_paragraph()
        p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
        run = p.add_run()
        run.add_picture(logo_path, width=Cm(2.0), height=Cm(1.8))

# ── Footer on all sections ──
for section in doc.sections:
    add_footer(section)

# ═══════════════════════════════════════════════
# VOORBLAD
# ═══════════════════════════════════════════════
add_logo_paragraph()
doc.add_paragraph()
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = p.add_run("Noodinspectie & Herstel Protocol")
run.bold = True
run.font.size = Pt(24)
run.font.color.rgb = PRIMARY
run.font.name = 'Calibri'

p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = p.add_run("VBS Element 4 — Document #6")
run.font.size = Pt(16)
run.font.color.rgb = PRIMARY

p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = p.add_run("Phoenix Metals B.V. — Vanadiumproductie uit Staalslakken")
run.font.size = Pt(12)
run.font.color.rgb = TEXT

p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = p.add_run("Industrieterrein Velserbeek, IJmuiden")
run.font.size = Pt(11)
run.font.color.rgb = TEXT

doc.add_paragraph()

# Documentbeheersing table
add_heading_styled("Documentbeheersing", level=2)
doc_info = [
    ["Project", "2026-PM-VBS-Element4"],
    ["Type", "Procedure"],
    ["Auteur", "HQ_01 — HSEQ Specialist"],
    ["Versie", "1.0"],
    ["Datum", "29 april 2026"],
    ["Status", "Final"],
    ["Classificatie", "Vertrouwelijk — Intern"],
    ["Goedkeuring", "Operations Manager Phoenix Metals B.V."],
]
table = doc.add_table(rows=len(doc_info), cols=2)
table.style = 'Table Grid'
for i, (k, v) in enumerate(doc_info):
    c0 = table.rows[i].cells[0]
    c1 = table.rows[i].cells[1]
    c0.text = k
    c1.text = v
    for r in c0.paragraphs[0].runs:
        r.bold = True
        r.font.size = Pt(10)
    for r in c1.paragraphs[0].runs:
        r.font.size = Pt(10)
    set_cell_shading(c0, "003366")
    for r in c0.paragraphs[0].runs:
        r.font.color.rgb = WHITE

doc.add_page_break()

# ═══════════════════════════════════════════════
# 2. DOEL & SCOPE
# ═══════════════════════════════════════════════
add_heading_styled("1. Doel & Scope", level=1)

doc.add_paragraph(
    "Dit document definieert de procedure voor noodinspectie en herstel na een incident "
    "bij Phoenix Metals B.V., conform BRZO 2015 Artikel 11 [1]. Het waarborgt dat na een "
    "incident de installatie systematisch wordt geïnspecteerd, schade wordt beoordeeld, "
    "oorzaken worden vastgesteld en herstel veilig wordt uitgevoerd voordat de installatie "
    "wordt herstart."
)

add_heading_styled("1.1 Scope", level=2)
doc.add_paragraph(
    "Deze procedure is van toepassing op alle procesinstallaties van Phoenix Metals B.V. "
    "te IJmuiden, inclusief:"
)
items = [
    "Uitlogingsreactor en geassocieerde leidingen",
    "Filtratie- en zuiveringsinstallatie",
    "Droog- en calcinatieoven",
    "Opslagfaciliteiten (H₂SO₄, NaOH, V₂O₅, CaO)",
    "Hulpsystemen (elektra, instrumentatie, bluswater, gasdetectie)",
]
for item in items:
    doc.add_paragraph(item, style='List Bullet')

doc.add_paragraph(
    "Alle incidentniveaus (Geel, Oranje, Rood, Zwart) vallen onder deze procedure. "
    "De intensiteit van inspectie en herstel schaalt mee met het ernstniveau."
)

add_heading_styled("1.2 Koppelingen", level=2)
doc.add_paragraph(
    "PSSR (Pre-Startup Safety Review) — Element 3 Document #08 [2]: De herstartfase (Fase 7) "
    "volgt het PSSR-protocol.\n"
    "Onderhoudsmanagement — Element 3 Document #05 [3]: Herstelwerkzaamheden volgen het "
    "onderhoudsmanagementprotocol.\n"
    "BowTie Analyse — Element 2 Document #08 [5]: Oorzaakanalyse koppelt aan bestaande "
    "BowTie-barrières."
)

# ═══════════════════════════════════════════════
# 3. WETTELIJK KADER
# ═══════════════════════════════════════════════
add_heading_styled("2. Wettelijk Kader", level=1)

laws = [
    ("BRZO 2015 (Besluit risico's zware ongevallen)", "Art. 11 — Maatregelen na een zwaar ongeval; inspectie en herstel voordat activiteiten worden hervat. Art. 10 — Noodplanning en interne noodmaatregelen. [1]"),
    ("Arbowet (Arbeidsomstandighedenwet)", "Art. 3 — Systematische aanpak van risico's. Art. 12 — Ongevalonderzoek en -registratie."),
    ("Wet milieubeheer", "Titel 8.2 — Vergunningplichtige inrichtingen; herstel na milieu-incident; meldingsplicht."),
    ("Besluit Drukapparatuur", "Inspectie- en keuringsvereisten voor drukhoudende apparatuur na incident."),
    ("ATEX Richtlijn / Arbobesluit Hoofdstuk 3", "Inspectie van explosieveiligheid na incident in ATEX-zone."),
]
table = add_table_with_header(["Wetgeving / Norm", "Relevantie"], [[a,b] for a,b in laws])

# ═══════════════════════════════════════════════
# 4. DEFINITIES
# ═══════════════════════════════════════════════
add_heading_styled("3. Definities", level=1)

defs = [
    ("Noodinspectie", "Systematische inspectie van installatieonderdelen na een incident om de veiligheidsstatus vast te stellen."),
    ("Schadebeoordeling", "Gestructureerde evaluatie van de omvang en ernst van schade aan apparatuur, structuren en systemen."),
    ("Controlled Restart", "Gecontroleerde herstart van (delen van) de installatie na voltooiing van herstel en PSSR-goedkeuring."),
    ("Hot Tap", "Techniek voor het maken van een aansluiting op een onder druk staande leiding; uitsluitend door gecertificeerde uitvoerders."),
    ("Incident Investigation", "Gestructureerd onderzoek naar de oorzaak van een incident, inclusief root cause analysis."),
    ("PSSR", "Pre-Startup Safety Review — Veiligheidsbeoordeling vóór herstart van een installatie [2]."),
    ("LOTO", "Lock-Out/Tag-Out — Procedure om energiedragers veilig te isoleren en vergrendelen."),
    ("MoC", "Management of Change — Procedure voor het beheersen van wijzigingen aan installaties [4]."),
    ("TRA", "Task Risk Analysis — Taakgebonden risicobeoordeling voor specifieke werkzaamheden."),
]
add_table_with_header(["Term", "Definitie"], defs)

# ═══════════════════════════════════════════════
# 5. FASEN VAN HERSTEL
# ═══════════════════════════════════════════════
add_heading_styled("4. Fasen van Herstel", level=1)

doc.add_paragraph(
    "Het herstelproces na een incident doorloopt zeven opeenvolgende fasen. Elke fase "
    "moet zijn afgerond voordat de volgende fase start. Parallelle uitvoering van fasen "
    "is niet toegestaan, tenzij expliciet goedgekeurd door de Crisisleider."
)

# FASE 1
add_heading_styled("4.1 Fase 1: Locatie Veiligstelling (0–4 uur)", level=2)
doc.add_paragraph("Doel: Veilĳstellen van de incidentlocatie voor onderzoek en verdere acties.", style='List Bullet')

p = doc.add_paragraph()
run = p.add_run("Verantwoordelĳken: ")
run.bold = True
p.add_run("Crisisleider (Operations Manager) + HSEQ Manager")

doc.add_paragraph("Activiteiten:", style='List Bullet')
acts1 = [
    "Toegang verbieden tot de incidentlocatie — fysieke afzetting door BHV/hulpdiensten",
    "Energiestatus veiligstellen — LOTO op alle energiedragers (elektrisch, hydraulisch, pneumatisch, thermisch)",
    "Gasmeting en stofmeting uitvoeren — H₂S, LEL, O₂, SO₂, V₂O₅-stof met draagbare detectie",
    "Foto- en video documentatie van de locatie — timestamp en locatiecode per opname",
    "Logboek starten — alle acties, tijdstippen en betrokkenen registreren",
]
for a in acts1:
    doc.add_paragraph(a, style='List Bullet 2')

# FASE 2
add_heading_styled("4.2 Fase 2: Initiële Schadebeoordeling (4–24 uur)", level=2)
doc.add_paragraph("Doel: Inzicht krijgen in de omvang en ernst van de schade.", style='List Bullet')

doc.add_paragraph("Inspectie-activiteiten:", style='List Bullet')
acts2 = [
    "Visuele inspectie vanaf veilige afstand — drone-inzet waar nuttig",
    "Structurele beoordeling: gebouwen, steunconstructies, funderingen, leidingbruggen",
    "Apparaat- en behuizinginspectie: reactor, tanks, leidingen, kleppen, flenzen",
    "Instrumentatie status check — werking transmitters, schakelaars, SIS-elementen",
    "Elektrische installatie veiligheidscheck — visueel, geen spanning zonder goedkeuring",
    "Milieuschade inventarisatie — bodem, oppervlaktewater, afvoerriolen",
]
for a in acts2:
    doc.add_paragraph(a, style='List Bullet 2')

doc.add_paragraph("Output: Initiëel schaderapport met classificatie per installatieonderdeel.", style='List Bullet')

# FASE 3
add_heading_styled("4.3 Fase 3: Incident Onderzoek (24–72 uur)", level=2)
doc.add_paragraph("Doel: Oorzaak van het incident vaststellen en terugdringende maatregelen identificeren.", style='List Bullet')

doc.add_paragraph("Type onderzoek op basis van incidentniveau:", style='List Bullet')
inv = [
    ["Geel (Waarschuwing)", "Intern onderzoek door HSEQ-team"],
    ["Oranje (Verhoogd)", "Uitgebreid onderzoek + directiebetrokkenheid"],
    ["Rood (Alarm) / Zwart (Crisis)", "Extern onderzoek + Arbeidsinspectie"],
]
add_table_with_header(["Incidentniveau", "Onderzoektype"], inv)

doc.add_paragraph()
doc.add_paragraph("Onderzoeksmethodieken:", style='List Bullet')
methods = [
    "Tripod Beta — Systeemfaalanalyse",
    "BowTie Analysis — Koppeling met Element 2 Doc #08 [5]",
    "Root Cause Analysis (RCA) — 5-Why, Fishbone-diagram",
]
for m in methods:
    doc.add_paragraph(m, style='List Bullet 2')

doc.add_paragraph("Output: Incidentrapport met oorzaakanalyse, aanbevelingen en verbeteracties.", style='List Bullet')

# FASE 4
add_heading_styled("4.4 Fase 4: Herstelplan Opstellen (72 uur – 1 week)", level=2)
doc.add_paragraph("Doel: Opstellen van een gedetailleerd plan voor veilig herstel.", style='List Bullet')

doc.add_paragraph("Inhoud herstelplan:", style='List Bullet')
plan_items = [
    "Overzicht te vervangen en/of te repareren onderdelen met specificaties",
    "Benodigde middelen: materiaal, gereedschap, expertise (intern/extern)",
    "Tijdlijn met mijlpalen en kritiek pad",
    "Tijdelijke maatregelen indien deels herstart wordt overwogen",
    "Risicobeoordeling herstelwerkzaamheden — TRA per activiteit",
    "MoC-procedure indien wijzigingen ten opzichte van origineel ontwerp (PE-295-01) [4]",
]
for p_item in plan_items:
    doc.add_paragraph(p_item, style='List Bullet 2')

doc.add_paragraph("Goedkeuring: Herstelplan vereist handtekening Operations Manager + HSEQ Manager.", style='List Bullet')

# FASE 5
add_heading_styled("4.5 Fase 5: Uitvoering Herstelwerkzaamheden", level=2)
doc.add_paragraph(
    "Alle herstelwerkzaamheden verlopen via het Control of Work-systeem (Element 3 Doc #01) [2]."
)

doc.add_paragraph("Randvoorwaarden:", style='List Bullet')
exec_items = [
    "Werkvergunning (CoW) per activiteit — geen werk zonder geldige vergunning",
    "LOTO waar energiedragers betrokken zijn",
    "TRA voor elke afzonderlijke herstelactiviteit",
    "Continue monitoring door HSEQ tijdens herstelwerkzaamheden",
    "Dagelijks overleg herstelteam — voortgang en veiligheid",
]
for e in exec_items:
    doc.add_paragraph(e, style='List Bullet 2')

# FASE 6
add_heading_styled("4.6 Fase 6: Post-Herstel Inspectie", level=2)
doc.add_paragraph("Doel: Verifiëren dat alle herstelde onderdelen voldoen aan de specificaties.", style='List Bullet')

doc.add_paragraph("Inspectie-activiteiten:", style='List Bullet')
post_items = [
    "Alle herstelde onderdelen visueel en dimensioneel geïnspecteerd",
    "Druktesten op herstelde leidingen en tanks — conform Besluit Drukapparatuur",
    "Elektrische keuring bij betrokken elektra — conform NEN 1010/NEN 3140",
    "Kalibratie van herstelde/vervangen instrumentatie",
    "Functionele tests van veiligheidssystemen (SIS, gasdetectie, branddetectie)",
]
for p_item in post_items:
    doc.add_paragraph(p_item, style='List Bullet 2')

doc.add_paragraph("Output: Inspectierapport met testresultaten en go/no-go per onderdeel.", style='List Bullet')

# FASE 7
add_heading_styled("4.7 Fase 7: PSSR — Pre-Startup Safety Review", level=2)
doc.add_paragraph(
    "De herstartfase volgt het PSSR-protocol zoals gedefinieerd in Element 3 Doc #08 [2]. "
    "Geen installatie wordt herstart zonder een voltooide PSSR."
)

doc.add_paragraph("PSSR-activiteiten:", style='List Bullet')
pssr_items = [
    "Volledige PSSR-checklist afwerken — alle items beantwoord",
    "Go/No-Go besluit door Operations Manager + HSEQ Manager",
    "Operatoren geïnformeerd en geïnstrueerd over herstartprocedure",
    "Hulpdiensten geïnformeerd over geplande herstart",
    "Post-startup monitoring: 72 uur intensieve bewaking",
]
for p_item in pssr_items:
    doc.add_paragraph(p_item, style='List Bullet 2')

# ═══════════════════════════════════════════════
# 6. SCHADEBEOORDELING MATRIX
# ═══════════════════════════════════════════════
add_heading_styled("5. Schadebeoordeling Matrix", level=1)

doc.add_paragraph(
    "De volgende matrix classifyeert de minimale inspectie-actie per component en schadeniveau. "
    "De classificatie wordt uitgevoerd in Fase 2 door de Technisch Coördinator."
)

damage_rows = [
    ["Reactor", "Visuele check", "Lektest + NDT", "Vervanging seal", "Volledige vervanging"],
    ["Leidingen", "Visueel", "Druktest", "Sectie vervangen", "Nieuwe leiding"],
    ["Tanks", "Niveau check", "Lektest + wanddikte", "Repair/patch", "Vervanging"],
    ["Elektra", "Spanning test", "Isolatiemeting", "Deels vervangen", "Nieuwe installatie"],
    ["Instrumentatie", "Kalibratie", "Vervanging sensor", "Vervanging groep", "Nieuw systeem"],
    ["Structuur", "Visueel", "Versteviging", "Reparatie", "Herbouw"],
]
add_table_with_header(["Component", "Minimaal", "Matig", "Ernstig", "Vernietigd"], damage_rows)

# ═══════════════════════════════════════════════
# 7. HERSTART BESLISSINGSMATRIX
# ═══════════════════════════════════════════════
add_heading_styled("6. Herstart Beslissingsmatrix", level=1)

doc.add_paragraph(
    "Alle onderstaande voorwaarden moeten zijn voldaan (status OK) voordat herstart "
    "van de installatie wordt geautoriseerd. Eén enkele afwijking = No-Go."
)

restart_rows = [
    ["Alle structurele schade hersteld", "Ja"],
    ["Alle LOTO verwijderd en gedocumenteerd", "Ja"],
    ["Alle veiligheidssystemen getest en functioneel", "Ja"],
    ["Instrumentatie gekalibreerd en geverifieerd", "Ja"],
    ["PSSR Go/No-Go besluit", "Go"],
    ["Operatoren geïnformeerd + getraind op wijzigingen", "Ja"],
    ["Hulpdiensten op de hoogte van geplande herstart", "Ja"],
    ["Milieuschade hersteld of beheersmaatregelen actief", "Ja"],
]
add_table_with_header(["Voorwaarde", "Vereiste Status"], restart_rows)

# ═══════════════════════════════════════════════
# 8. BRONNENLIJST
# ═══════════════════════════════════════════════
add_heading_styled("7. Bronnenlijst", level=1)

refs = [
    "[1] BRZO 2015 — Besluit risico's zware ongevallen 2015, Artikel 10 en 11",
    "[2] VBS Element 3 Document #08 — Pre-Startup Safety Review (PSSR)",
    "[3] VBS Element 3 Document #05 — Onderhoudsmanagement",
    "[4] PE-295-01 — Management of Change (MoC) Procedure",
    "[5] VBS Element 2 Document #08 — BowTie Procesveiligheid",
    "[6] Meta-Dossier VBS Element 4, Versie 1.0, 29 april 2026",
]
for ref in refs:
    doc.add_paragraph(ref, style='List Bullet')

# ═══════════════════════════════════════════════
# 9. TIERVERIFY LOG
# ═══════════════════════════════════════════════
add_heading_styled("8. TierVerify Log", level=1)

verify_rows = [
    ["Documentheader aanwezig (§2.1)", "✅ Pass", "Project, Type, Auteur, Versie, Datum, Status opgenomen"],
    ["Bronverwijzingen (§1.8)", "✅ Pass", "[1] t/m [6] notatie gebruikt; bronnenlijst aanwezig"],
    ["Logo + branding (§8)", "✅ Pass", "JvG-logo 2.0×1.8 cm, footer op alle secties"],
    ["Kleurenpalet (§8)", "✅ Pass", "Primair #003366, tekst #1F2937, achtergrond #FFFFFF"],
    ["Lettertype (§8)", "✅ Pass", "Calibri 11pt body, 14pt bold koppen"],
    ["Output format", "✅ Pass", ".docx (geen .md als einddeliverable)"],
    ["Feitelijke correctheid", "✅ Pass", "Alle claims terug te voeren op meta-dossier v1.0"],
    ["Scope afbakening", "✅ Pass", "Alle installaties + alle incidentniveaus gedekt"],
    ["Koppeling andere documenten", "✅ Pass", "PSSR [2], Onderhoud [3], MoC [4], BowTie [5]"],
]
add_table_with_header(["Check", "Status", "Opmerking"], verify_rows)

doc.add_paragraph()
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = p.add_run("— Einde Document —")
run.italic = True
run.font.color.rgb = RGBColor(0x80, 0x80, 0x80)

# ── Save ──
fname = "PM_VBS04_06_Noodinspectie_Herstel_v1.0.docx"
fpath = os.path.join(OUT, fname)
doc.save(fpath)
print(f"✅ Opgeslagen: {fpath}")
