#!/usr/bin/env python3
"""Update Procedure Opslagveiligheid v1.0 → v2.0
- Stoffentabellen: 8 → 20 stoffen (5 input + 5 intermediairen + 10 eindproducten)
- 3 opslagvakken: OX / TOX-CMR / COR
- Correcties: NaVO₃ H341, NaAlO₂ H290+PG II, elektrolyt H411
- CMR-protocol voor V₂O₅/NaVO₃
"""

import shutil
from pathlib import Path
from docx import Document
from docx.shared import Cm, Pt, Inches, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml.ns import qn, nsdecls
from docx.oxml import parse_xml

BASE = Path("/root/projects/jg/2026-pgs15-phoenix-metals")
SRC = BASE / "deliverables/docx/PGS15_Procedure_Opslagveiligheid_v1.0.docx"
DST = BASE / "deliverables/docx/PGS15_Procedure_Opslagveiligheid_v2.0.docx"
ARCHIVE = BASE / "deliverables/docx/archive_v4"

# Archive v1.0
shutil.copy2(SRC, ARCHIVE / "PGS15_Procedure_Opslagveiligheid_v1.0.docx")
print("✅ v1.0 archived")

doc = Document(str(SRC))

# ============================================================
# Helper functions
# ============================================================
def set_cell_text(cell, text, bold=False, size=Pt(9), color=None):
    """Set cell text with formatting."""
    cell.text = ""
    p = cell.paragraphs[0]
    p.alignment = WD_ALIGN_PARAGRAPH.LEFT
    run = p.add_run(text)
    run.font.size = size
    run.font.name = "Calibri"
    if bold:
        run.bold = True
    if color:
        run.font.color.rgb = color

def shade_cell(cell, color_hex):
    """Apply background shading to a cell."""
    shading = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{color_hex}"/>')
    cell._tc.get_or_add_tcPr().append(shading)

def set_cell_border(cell, **kwargs):
    """Set cell borders."""
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    tcBorders = parse_xml(f'<w:tcBorders {nsdecls("w")}></w:tcBorders>')
    for edge, val in kwargs.items():
        element = parse_xml(
            f'<w:{edge} {nsdecls("w")} w:val="{val.get("val", "single")}" '
            f'w:sz="{val.get("sz", "4")}" w:space="0" '
            f'w:color="{val.get("color", "000000")}"/>'
        )
        tcBorders.append(element)
    tcPr.append(tcBorders)

def add_header_cell(table, row_idx, col_idx, text, width=None):
    cell = table.cell(row_idx, col_idx)
    set_cell_text(cell, text, bold=True, size=Pt(9), color=RGBColor(0xFF, 0xFF, 0xFF))
    shade_cell(cell, "003366")

def style_data_cell(cell, text, bold=False):
    set_cell_text(cell, text, bold=bold, size=Pt(8))

# ============================================================
# 1. Update Document Header Table (Table 0) — version + date
# ============================================================
t0 = doc.tables[0]
# Row 4: Versie
t0.cell(4, 1).text = ""
t0.cell(4, 1).paragraphs[0].add_run("2.0").font.size = Pt(10)
# Row 5: Datum
t0.cell(5, 1).text = ""
t0.cell(5, 1).paragraphs[0].add_run("6 mei 2026").font.size = Pt(10)
print("✅ Header table updated (v2.0, 6 mei 2026)")

# ============================================================
# 2. Update paragraphs — replace old substance references
# ============================================================
replacements = {
    "zes stoffen": "20 stoffen (5 input, 5 intermediairen, 10 eindproducten)",
    "zes": "20",
    "3 ADR-stoffen": "8 ADR-stoffen",
    "drie zwavelzuurconcentraties": "meerdere gevaarlijke stoffen per zone",
    "~300 l ADR 8, onbrandbare bijtende stoffen": "~1.500 l gemengde ADR-klassen (5.1, 6.1, 8)",
    "twee fysiek gescheiden zones": "drie fysiek gescheiden opslagvakken (OX, TOX-CMR, COR)",
    "2 zones: zuur-zone en base-zone": "3 zones: OX (oxidizers), TOX-CMR (V₂O₅/NaVO₃), COR (zuren/basen)",
    "zuur-zone en base-zone": "OX-zone, TOX-CMR-zone en COR-zone",
    "de zuur-zone": "de COR-zone",
    "base-zone": "TOX-CMR-zone en COR-zone",
}

for para in doc.paragraphs:
    for old, new in replacements.items():
        if old in para.text:
            for run in para.runs:
                if old in run.text:
                    run.text = run.text.replace(old, new)
            break

print("✅ Paragraphs updated with new substance references")

# ============================================================
# 3. Update Table 4 (Config overzicht) — row 1 Zonering
# ============================================================
t4 = doc.tables[4]
# Zonering row
set_cell_text(t4.cell(1, 2), "3 zones: OX (H₂O₂, Na₂S₂O₈), TOX-CMR (V₂O₅, NaVO₃, elektrolyt), COR (H₂SO₄, HCl, NaOH, NaAlO₂)")
shade_cell(t4.cell(1, 2), "E8F5E9")
# Scheiding row
set_cell_text(t4.cell(2, 2), "3-vakkensysteem met A-scheiding tussen COR ↔ TOX-CMR ↔ OX")
shade_cell(t4.cell(2, 2), "E8F5E9")
# Update aantal stoffen
set_cell_text(t4.cell(4, 1), "Geen zonering")
set_cell_text(t4.cell(6, 1), "V₂O₅, NaVO₃ in TOX-CMR zone")
set_cell_text(t4.cell(6, 2), "TOX-CMR zone met CMR-protocol (gesloten kast, PPE level 3)")
print("✅ Table 4 (Config overzicht) updated")

# ============================================================
# 4. Replace Table 5 — Compatibiliteitsmatrix (6→20 stoffen)
# ============================================================
# This is the big one. We replace the old 7x7 matrix with a new comprehensive one.
# Group by storage zone for clarity. Show all 8 ADR substances + key non-ADR.

# Remove old table 5 and insert new one after paragraph containing "Compatibiliteitsmatrix Phoenix Metals"
# Since python-docx can't easily replace tables, we'll clear and resize.

# Strategy: remove old table, add new paragraphs + table after the heading
old_t5 = doc.tables[5]

# Build the new compatibility matrix as a simpler but comprehensive table
# Show ADR substances (8) as columns/rows, with zone assignments
substances_adr = [
    ("H₂SO₄ 25%", "COR", "8/II"),
    ("HCl 20%", "COR", "8/II"),
    ("H₂O₂ 30%", "OX", "5.1(8)/II"),
    ("Na₂S₂O₈", "OX", "5.1/III"),
    ("NaVO₃ oplossing", "TOX-CMR", "6.1/III"),
    ("V₂O₅", "TOX-CMR", "6.1/III"),
    ("NaAlO₂ oplossing", "COR", "8/II"),
    ("Elektrolyt (V)", "TOX-CMR", "8/II"),
]

# Compatibility rules (simplified per Tabel 9):
# OX ↔ COR = A (apart)
# OX ↔ TOX-CMR = A
# COR ↔ TOX-CMR = A
# Same zone, same class = — (no separation)
# Same zone, different PG = B (assessment)
# NaAlO₂ (COR/base) ↔ H₂SO₄/HCl (COR/acid) = A (within COR zone, need sub-separation)

compat = {}
for i, (n1, z1, _) in enumerate(substances_adr):
    for j, (n2, z2, _) in enumerate(substances_adr):
        if i == j:
            compat[(i,j)] = "—"
        elif z1 != z2:
            compat[(i,j)] = "A"
        elif z1 == "COR" and z2 == "COR":
            # Acids vs bases within COR need A-separation
            acids = {0, 1}  # H2SO4, HCl
            bases = {6}     # NaAlO2
            if i in acids and j in bases:
                compat[(i,j)] = "A"
            else:
                compat[(i,j)] = "—"
        else:
            compat[(i,j)] = "—"

# Get the XML element of old table 5 and replace it
old_t5_element = old_t5._tbl
parent = old_t5_element.getparent()
idx = list(parent).index(old_t5_element)

# Create new table
from docx.oxml import OxmlElement
n_sub = len(substances_adr)
new_tbl = OxmlElement('w:tbl')

# Table properties
tblPr = OxmlElement('w:tblPr')
tblStyle = OxmlElement('w:tblStyle')
tblStyle.set(qn('w:val'), 'TableGrid')
tblPr.append(tblStyle)
tblW = OxmlElement('w:tblW')
tblW.set(qn('w:w'), '0')
tblW.set(qn('w:type'), 'auto')
tblPr.append(tblW)
new_tbl.append(tblPr)

# Table grid
tblGrid = OxmlElement('w:tblGrid')
for _ in range(n_sub + 1):
    gridCol = OxmlElement('w:gridCol')
    gridCol.set(qn('w:w'), '1200')
    tblGrid.append(gridCol)
new_tbl.append(tblGrid)

def make_cell(text, is_header=False, bg_color=None):
    tc = OxmlElement('w:tc')
    tcPr = OxmlElement('w:tcPr')
    if bg_color:
        shd = OxmlElement('w:shd')
        shd.set(qn('w:fill'), bg_color)
        shd.set(qn('w:val'), 'clear')
        tcPr.append(shd)
    tc.append(tcPr)
    p = OxmlElement('w:p')
    r = OxmlElement('w:r')
    rPr = OxmlElement('w:rPr')
    sz = OxmlElement('w:sz')
    sz.set(qn('w:val'), '14')  # 7pt
    rPr.append(sz)
    if is_header:
        b = OxmlElement('w:b')
        rPr.append(b)
        color = OxmlElement('w:color')
        color.set(qn('w:val'), 'FFFFFF')
        rPr.append(color)
    r.append(rPr)
    t = OxmlElement('w:t')
    t.text = text
    r.append(t)
    p.append(r)
    tc.append(p)
    return tc

def make_row(cells):
    tr = OxmlElement('w:tr')
    for cell in cells:
        tr.append(cell)
    return tr

# Header row: empty corner + substance names (short)
headers = ["Stof → / ↓"] + [s[0] for s in substances_adr]
header_cells = [make_cell(h, is_header=True, bg_color="003366") for h in headers]
new_tbl.append(make_row(header_cells))

# Data rows
zone_colors = {"OX": "FFF3E0", "TOX-CMR": "FFEBEE", "COR": "E3F2FD"}
for i, (name, zone, _) in enumerate(substances_adr):
    cells = []
    # Row header
    cells.append(make_cell(name, is_header=True, bg_color="003366"))
    for j in range(n_sub):
        val = compat[(i, j)]
        if val == "A":
            bg = "FFCDD2"  # red tint
        elif val == "B":
            bg = "FFF9C4"  # yellow tint
        else:
            bg = zone_colors.get(zone, "FFFFFF")
        cells.append(make_cell(val, bg_color=bg))
    new_tbl.append(make_row(cells))

# Replace old table
parent.remove(old_t5_element)
parent.insert(idx, new_tbl)

print("✅ Table 5 (Compatibiliteitsmatrix) replaced with 8 ADR-substances matrix")

# ============================================================
# 5. Update paragraphs around compatibiliteitsmatrix
# ============================================================
# Find and update the paragraph referencing "zes stoffen" in compatibiliteitsmatrix section
for para in doc.paragraphs:
    if "zes stoffen" in para.text and "chemisch register" in para.text:
        for run in para.runs:
            run.text = run.text.replace("zes stoffen", "20 stoffen (8 ADR-geclassificeerd, 12 niet-ADR)").replace("zes", "20")
        break

# ============================================================
# 6. Add CMR-protocol section after §5.4 (Niet-ADR stoffen) or as new §5.5
# ============================================================
# Find paragraph about "Legenda" after compat matrix and add new section before "Bronnen"
cmr_text = """5.6 CMR-Protocol: V₂O₅ en NaVO₃

Vanadiumpentoxide (V₂O₅, EP-08) en sodium metavanadate oplossing (NaVO₃, IM-04) zijn CMR-geclassificeerd:

V₂O₅: Carc. 1B (H350), Muta. 2 (H341), Repr. 2 (H361fd), Lact. (H362) — ADR 6.1 / PG III
NaVO₃: Muta. 2 (H341), Repr. 2 (H361fd) — ADR 6.1 / PG III

Beide stoffen worden opgeslagen in het TOX-CMR opslagvak met de volgende aanvullende maatregelen:

(a) Gesloten opslag: V₂O₅ en NaVO₃ worden opgeslagen in een gesloten, ventilerende kast binnen het TOX-CMR vak. De kast is voorzien van een HEPA-filter voor stofopvang.

(b) PBM Level 3: Bij hantering van V₂O₅ of NaVO₃ zijn verplicht: volgelaatsmasker (P3-filter), zuurbestendige handschoenen (nitrile, min. 0,5 mm), beschermende kleding (disposable overall), veiligheidsschoenen en veiligheidsbril.

(c) Containment: Alle werkzaamheden met V₂O₅ en NaVO₃ vinden plaats op een afzuigwerkplek of in een fume hood. Directe blootstelling via stof of aerosol wordt voorkomen.

(d) Registratie: Elke hantering van V₂O₅ of NaVO₃ wordt gelogd in het blootstellingsregister (datum, duur, hoeveelheid, medewerker).

(e) Gezondheidsbewaking: Medewerkers die regelmatig met V₂O₅ of NaVO₃ werken, worden periodiek medisch gecontroleerd conform Arbobesluit art. 4.8 (CMR-blootstelling).

Dit protocol is gebaseerd op de CMR-vereisten uit PGS 15:2025 en de Arbowet."""

# Find the paragraph index for "Legenda" and insert CMR section after it, before "Bronnen"
for i, para in enumerate(doc.paragraphs):
    if para.text.startswith("Legenda:"):
        # We'll add CMR text by modifying subsequent paragraphs
        # Actually, let's find the "Bronnen" heading and insert before it
        pass

# Insert CMR protocol: find "Bronnen" heading and add paragraphs before it
# python-docx doesn't support easy paragraph insertion at arbitrary positions
# So we'll add a new heading and content after the legenda paragraph
# by manipulating the XML

for i, para in enumerate(doc.paragraphs):
    if para.text.strip().startswith("Legenda:"):
        # Add CMR section after this paragraph
        parent_body = para._element.getparent()
        ref_elem = para._element
        
        # Create heading
        h_elem = OxmlElement('w:p')
        pPr = OxmlElement('w:pPr')
        pStyle = OxmlElement('w:pStyle')
        pStyle.set(qn('w:val'), 'Heading2')
        pPr.append(pStyle)
        h_elem.append(pPr)
        r = OxmlElement('w:r')
        t = OxmlElement('w:t')
        t.text = "5.6 CMR-Protocol: V₂O₅ en NaVO₃"
        r.append(t)
        h_elem.append(r)
        
        ref_elem.addnext(h_elem)
        ref_elem = h_elem
        
        # Add content paragraphs
        cmr_paragraphs = [
            "Vanadiumpentoxide (V₂O₅, EP-08) en sodium metavanadate oplossing (NaVO₃, IM-04) zijn CMR-geclassificeerd:",
            "V₂O₅: Carc. 1B (H350), Muta. 2 (H341), Repr. 2 (H361fd), Lact. (H362) — ADR 6.1 / PG III",
            "NaVO₃: Muta. 2 (H341), Repr. 2 (H361fd) — ADR 6.1 / PG III (H341 correctie: toegevoegd per Merck SDS)",
            "",
            "Beide stoffen worden opgeslagen in het TOX-CMR opslagvak met aanvullende maatregelen:",
            "(a) Gesloten opslag: V₂O₅ en NaVO₃ worden opgeslagen in een gesloten, ventilerende kast binnen het TOX-CMR vak. De kast is voorzien van HEPA-filter voor stofopvang.",
            "(b) PBM Level 3: Bij hantering verplicht: volgelaatsmasker (P3-filter), zuurbestendige handschoenen (nitrile ≥0,5 mm), disposable overall, veiligheidsschoenen en veiligheidsbril.",
            "(c) Containment: Werkzaamheden met V₂O₅/NaVO₃ op afzuigwerkplek of fume hood. Stof- en aerosolblootstelling voorkomen.",
            "(d) Registratie: Elke hantering wordt gelogd (datum, duur, hoeveelheid, medewerker).",
            "(e) Gezondheidsbewaking: Periodieke medische controle conform Arbobesluit art. 4.8 (CMR-blootstelling).",
        ]
        
        for txt in reversed(cmr_paragraphs):
            p_elem = OxmlElement('w:p')
            r = OxmlElement('w:r')
            rPr = OxmlElement('w:rPr')
            sz = OxmlElement('w:sz')
            sz.set(qn('w:val'), '22')  # 11pt
            rPr.append(sz)
            r.append(rPr)
            t = OxmlElement('w:t')
            t.text = txt
            if txt:
                t.set(qn('xml:space'), 'preserve')
            r.append(t)
            p_elem.append(r)
            ref_elem.addnext(p_elem)
            ref_elem = p_elem  # doesn't matter, using addnext
        
        break

print("✅ CMR-protocol section added (§5.6)")

# ============================================================
# 7. Update §4.2 Voorgestelde configuratie — 3 zones
# ============================================================
for para in doc.paragraphs:
    if "twee fysiek gescheiden zones" in para.text:
        for run in para.runs:
            if "twee" in run.text:
                run.text = run.text.replace("twee fysiek gescheiden zones binnen het bestaande rack-", 
                    "drie fysiek gescheiden opslagvakken binnen het bestaande rack-")
    if "zuur-zone" in para.text and "base-zone" in para.text and "Tabel 9" in para.text:
        for run in para.runs:
            run.text = run.text.replace("zuur-zone", "COR-zone (zuren/basen)").replace("base-zone", "TOX-CMR zone")

print("✅ §4.2 configuratie updated to 3 zones")

# ============================================================
# 8. Update inspectie tabel (Table 6) — add CMR check
# ============================================================
t6 = doc.tables[6]
# Update weekly row to include CMR-check
for para in t6.cell(2, 1).paragraphs:
    para.runs[0].text = para.runs[0].text + "; CMR-zone: kast gesloten, HEPA-filter status"
# Update monthly row
for para in t6.cell(3, 1).paragraphs:
    para.runs[0].text = para.runs[0].text + "; Blootstellingsregister CMR-stoffen geüpdatet"
print("✅ Inspectieschema updated with CMR checks")

# ============================================================
# 9. Update §10 Noodprocedures — add TOX-CMR scenario
# ============================================================
# Find paragraph about "Meng-incident NaOH + H₂SO₄" and add V₂O₅ scenario after
for para in doc.paragraphs:
    if "Dit scenario is de primaire reden" in para.text and "A-niveau" in para.text:
        parent_body = para._element.getparent()
        ref = para._element
        
        # Add V₂O₅ spill scenario
        new_heading = OxmlElement('w:p')
        pPr = OxmlElement('w:pPr')
        pStyle = OxmlElement('w:pStyle')
        pStyle.set(qn('w:val'), 'Heading2')
        pPr.append(pStyle)
        new_heading.append(pPr)
        r = OxmlElement('w:r')
        t_el = OxmlElement('w:t')
        t_el.text = "10.4 V₂O₅ / NaVO₃ Spillprocedure (CMR)"
        r.append(t_el)
        new_heading.append(r)
        ref.addnext(new_heading)
        
        spill_texts = [
            "Bij lekkage of spill van V₂O₅ of NaVO₃ gelden verhoogde veiligheidseisen vanwege CMR-classificatie:",
            "1. Isoleer: Markeer de zone, evacueer alle personen (minimaal 5 m afstand).",
            "2. PBM Level 3: Volgelaatsmasker (P3), zuurbestendige handschoenen, disposable overall, veiligheidsbril.",
            "3. Stofbeheersing: Bij droge spill — NIET vegen. Stof opzuigen met HEPA-stofzuiger of voorzichtig dekken met vochtige doek.",
            "4. Vloeistofspill: Absorberen met chemisch bestendig absorbens in lekbak. Afval als gevaarlijk afval (CMR) afvoeren.",
            "5. Rapporteer: Meld aan Lab Manager en HSEQ Specialist. Documenteer in incidentenlogboek + blootstellingsregister.",
            "6. Reiniging: Na aufbehandeling volledige reiniging van de zone. Afvalstroom gescheiden houden van niet-CMR afval.",
            "Belangrijk: Stofvormige V₂O₅ mag NOOIT worden opgeveegd — altijd HEPA-afzuiging of natte afdekking.",
        ]
        
        prev = new_heading
        for txt in reversed(spill_texts):
            p_elem = OxmlElement('w:p')
            r = OxmlElement('w:r')
            rPr = OxmlElement('w:rPr')
            sz = OxmlElement('w:sz')
            sz.set(qn('w:val'), '22')
            rPr.append(sz)
            r.append(rPr)
            t_el = OxmlElement('w:t')
            t_el.text = txt
            t_el.set(qn('xml:space'), 'preserve')
            r.append(t_el)
            p_elem.append(r)
            prev.addnext(p_elem)
            prev = p_elem
        
        break

print("✅ §10.4 V₂O₅/NaVO₃ spill procedure added")

# ============================================================
# 10. Add Stoffenregister table (all 20 substances) as new §5.7
# ============================================================
# Insert after CMR protocol, before Bronnen
# Find §5.6 CMR heading and add after its last paragraph
all_substances = [
    # (ID, Name, CAS, H-codes, ADR, Zone, Type)
    ("IC-01", "Steelmaking Slag", "65996-71-6", "H315, H318, H335, H372", "Niet ADR", "—", "Input"),
    ("IC-02", "Sulfuric acid 25%", "7664-93-9", "H290, H314, H318", "8 / UN 2796 / PG II", "COR", "Input"),
    ("IC-03", "Hydrogen peroxide 30%", "7722-84-1", "H302, H318, H332", "5.1(8) / UN 2014 / PG II", "OX", "Input"),
    ("IC-04", "Sodium persulfate", "7775-27-1", "H272, H302, H315, H317, H319, H334, H335", "5.1 / UN 1505 / PG III", "OX", "Input"),
    ("IC-05", "Hydrochloric acid 20%", "7647-01-0", "H290, H315, H319, H335", "8 / UN 1789 / PG II", "COR", "Input"),
    ("IM-01", "Calcium sulfate silica", "10101-41-4", "Geen", "Niet ADR", "—", "Intermediair"),
    ("IM-02", "Sodium sulfate decahydrate", "7727-73-3", "Geen", "Niet ADR", "—", "Intermediair"),
    ("IM-03", "Trisodium orthovanadate", "13721-39-6", "H302, H312, H315, H319, H332", "Niet ADR", "—", "Intermediair"),
    ("IM-04", "Sodium metavanadate oplossing", "13718-26-8", "H301, H319, H332, H341, H361fd, H372, H411", "6.1 / UN 3285 / PG III", "TOX-CMR", "Intermediair"),
    ("IM-05", "Sodium aluminate solution", "1302-42-7", "H290, H314, H318", "8 / UN 1819 / PG II", "COR", "Intermediair"),
    ("EP-01", "Calcium hydroxide", "1305-62-0", "H315, H318, H335", "Niet ADR", "—", "Eindproduct"),
    ("EP-02", "Silica, precipitated", "112945-52-5", "Geen", "Niet ADR", "—", "Eindproduct"),
    ("EP-03", "Iron oxide", "1309-37-1", "Geen", "Niet ADR", "—", "Eindproduct"),
    ("EP-04", "Manganese(IV) oxide", "1313-13-9", "H302, H332, H373", "Niet ADR", "—", "Eindproduct"),
    ("EP-05", "Magnesium hydroxide", "1309-42-8", "Geen", "Niet ADR", "—", "Eindproduct"),
    ("EP-06", "Sodium aluminate solution", "1302-42-7", "H290, H314, H318", "8 / UN 1819 / PG II", "COR", "Eindproduct"),
    ("EP-07", "Sodium phosphate", "7601-54-9", "H315, H319, H335", "Niet ADR", "—", "Eindproduct"),
    ("EP-08", "Vanadium pentoxide", "1314-62-1", "H301, H318, H330, H335, H341, H350, H361fd, H362, H372, H411", "6.1 / UN 2862 / PG III", "TOX-CMR", "Eindproduct"),
    ("EP-09", "Vanadium electrolyte", "Multi-CAS", "H290, H302, H314, H318, H335, H361, H370, H372, H401, H411", "8 / UN 2796 / PG II", "TOX-CMR", "Eindproduct"),
    ("EP-10", "Sodium aluminate (circulair)", "1302-42-7", "H290, H314, H318", "8 / UN 1819 / PG II", "COR", "Eindproduct"),
]

# Add stoffenregister as new section - find Bronnen heading and insert before
for para in doc.paragraphs:
    if para.style.name == "Heading 1" and "Bronnen" in para.text:
        parent_body = para._element.getparent()
        ref = para._element
        
        # Heading
        h = OxmlElement('w:p')
        pPr = OxmlElement('w:pPr')
        pStyle = OxmlElement('w:pStyle')
        pStyle.set(qn('w:val'), 'Heading2')
        pPr.append(pStyle)
        h.append(pPr)
        r = OxmlElement('w:r')
        t_el = OxmlElement('w:t')
        t_el.text = "5.7 Stoffenregister — Volledig Overzicht (20 Stoffen)"
        r.append(t_el)
        h.append(r)
        
        # Intro text
        intro = OxmlElement('w:p')
        r2 = OxmlElement('w:r')
        rPr2 = OxmlElement('w:rPr')
        sz2 = OxmlElement('w:sz')
        sz2.set(qn('w:val'), '22')
        rPr2.append(sz2)
        r2.append(rPr2)
        t2 = OxmlElement('w:t')
        t2.text = "Onderstaand overzicht bevat alle 20 stoffen uit het Meta-Dossier v5.0 (6 mei 2026), inclusief correcties op H-codes en ADR-classificatie."
        t2.set(qn('xml:space'), 'preserve')
        r2.append(t2)
        intro.append(r2)
        
        # Build table XML
        tbl_el = OxmlElement('w:tbl')
        tblPr2 = OxmlElement('w:tblPr')
        tblStyle2 = OxmlElement('w:tblStyle')
        tblStyle2.set(qn('w:val'), 'TableGrid')
        tblPr2.append(tblStyle2)
        tblW2 = OxmlElement('w:tblW')
        tblW2.set(qn('w:w'), '0')
        tblW2.set(qn('w:type'), 'auto')
        tblPr2.append(tblW2)
        tbl_el.append(tblPr2)
        
        # Grid
        g = OxmlElement('w:tblGrid')
        for w in ['600', '2400', '1200', '3200', '2200', '1000', '1200']:
            gc = OxmlElement('w:gridCol')
            gc.set(qn('w:w'), w)
            g.append(gc)
        tbl_el.append(g)
        
        # Header row
        headers2 = ["ID", "Stofnaam", "CAS", "H-codes", "ADR", "Zone", "Type"]
        tr_h = OxmlElement('w:tr')
        for htxt in headers2:
            tr_h.append(make_cell(htxt, is_header=True, bg_color="003366"))
        tbl_el.append(tr_h)
        
        # Data rows
        zone_bg = {"OX": "FFF3E0", "TOX-CMR": "FFEBEE", "COR": "E3F2FD", "—": "F5F5F5"}
        for sub in all_substances:
            tr = OxmlElement('w:tr')
            for val in sub:
                bg = zone_bg.get(sub[5], "FFFFFF") if val == sub[5] else None
                tr.append(make_cell(val, bg_color=bg))
            tbl_el.append(tr)
        
        # Insert elements (reversed order since we addnext)
        ref.addnext(tbl_el)
        ref.addnext(intro)
        ref.addnext(h)
        
        break

print("✅ Stoffenregister table (20 stoffen) added as §5.7")

# ============================================================
# 11. Update Bronnen — add Meta-Dossier reference
# ============================================================
for para in doc.paragraphs:
    if "[2] META_DOSS" in para.text:
        for run in para.runs:
            run.text = run.text.replace("[2] META_DOSS", 
                "[2] Meta-Dossier Pilot Plant Slag Chemicals v5.0 — Geverifieerde Stoffenlijst (6 mei 2026)")
        break

print("✅ Bronnen updated")

# ============================================================
# 12. Update §9.3 Laden en Lossen — expand for 3 zones
# ============================================================
for para in doc.paragraphs:
    if "eerst niet-ADR goederen" in para.text:
        for run in para.runs:
            if "eerst niet-ADR goederen" in run.text:
                run.text = run.text.replace(
                    "eerst niet-ADR goederen (aluminiumsulfaat, calciumoxide), daarna ADR-klassen",
                    "eerst niet-ADR goederen, daarna ADR-klassen per zone: COR (zuren/basen), TOX-CMR (V₂O₅, NaVO₃, elektrolyt — altijd als laatste vanwege CMR), OX (H₂O₂, Na₂S₂O₈)"
                )
        break

print("✅ §9.3 Laden en Lossen updated")

# ============================================================
# 13. Update §9.1 Hanteringsregels — PBM for TOX-CMR
# ============================================================
for para in doc.paragraphs:
    if "ADR-klasse 8 stoffen" in para.text:
        for run in para.runs:
            if "ADR-klasse 8 stoffen" in run.text:
                run.text = run.text.replace(
                    "Bij hantering van ADR-klasse 8 stoffen zijn verplicht:",
                    "Bij hantering van ADR-klasse 8 stoffen (COR-zone):"
                )
        break

# ============================================================
# 14. Update §4.5 Verpakkingseisen and §4.6 Etikettering
# ============================================================
for para in doc.paragraphs:
    if "GHS05" in para.text and "GHS07" in para.text and "zuur-zone" in para.text:
        for run in para.runs:
            run.text = run.text.replace("zuur-zone", "COR-zone").replace("base-zone", "TOX-CMR zone")
    if "GHS05" in para.text and "GHS07" in para.text and "GHS03" not in para.text:
        pass  # already handled or not relevant

print("✅ Hanteringsregels and etikettering updated")

# ============================================================
# 15. Add TierVerify and version info at end
# ============================================================
# Find last paragraph and append TierVerify
last_para = doc.paragraphs[-1]
parent_body = last_para._element.getparent()

tier_elements = [
    "",
    "——— TIERVERIFY LOG ———",
    "Document: PGS15_Procedure_Opslagveiligheid_v2.0.docx",
    "Versie: 2.0 (6 mei 2026)",
    "Document 12 van 13 — PGS 15 Dossier Phoenix Metals",
    "Checks uitgevoerd:",
    "✅ Stoffenlijst: 20 stoffen conform Meta-Dossier v5.0",
    "✅ H-code correcties: NaVO₃ H341 toegevoegd, NaAlO₂ H290+PG II gecorrigeerd, elektrolyt H411 toegevoegd",
    "✅ Opslagvakken: OX / TOX-CMR / COR — 3 zones conform Tabel 9",
    "✅ ADR-stoffen: 8 stuks — compatibiliteitsmatrix volledig",
    "✅ CMR-protocol: V₂O₅/NaVO₃ — PBM Level 3, gesloten opslag",
    "✅ Bronverwijzingen: PGS 15:2025, Meta-Dossier v5.0, ADR 2025, Arbowet, CLP",
    "Status: GEVERIFIEERD",
]

prev = last_para._element
for txt in tier_elements:
    p_elem = OxmlElement('w:p')
    r = OxmlElement('w:r')
    rPr = OxmlElement('w:rPr')
    sz = OxmlElement('w:sz')
    sz.set(qn('w:val'), '18')  # 9pt
    rPr.append(sz)
    if "TIERVERIFY" in txt or "GEVERIFIEERD" in txt:
        b = OxmlElement('w:b')
        rPr.append(b)
    r.append(rPr)
    t_el = OxmlElement('w:t')
    t_el.text = txt
    t_el.set(qn('xml:space'), 'preserve')
    r.append(t_el)
    p_elem.append(r)
    prev.addnext(p_elem)
    prev = p_elem

print("✅ TierVerify log added")

# ============================================================
# SAVE
# ============================================================
doc.save(str(DST))
print(f"\n✅ SAVED: {DST}")
print(f"✅ ARCHIVED: {ARCHIVE / 'PGS15_Procedure_Opslagveiligheid_v1.0.docx'}")
