#!/usr/bin/env python3
"""Update PGS15_Procedure_Opslagveiligheid v1.0 → v2.0 — CORRECTED"""
import shutil
from pathlib import Path
from docx import Document
from docx.shared import Pt, Cm
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
from lxml import etree
import copy

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"

doc = Document(str(SRC))

# === 1. Fix header version/date ===
t0 = doc.tables[0]
for cell_idx, val in [(4, "2.0"), (5, "6 mei 2026")]:
    cell = t0.cell(cell_idx, 1)
    p = cell.paragraphs[0]
    for r in p.runs:
        r.text = ''
    if p.runs:
        p.runs[0].text = val
    else:
        p.add_run(val)

# === 2. Replace compat matrix (table 5) in-place ===
# Build 20-substance compat matrix
substances = [
    ("IC-01 Slagspecie", "—"),
    ("IC-02 H₂SO₄ 25%", "8"),
    ("IC-03 H₂O₂ 30%", "5.1"),
    ("IC-04 Na₂S₂O₈", "5.1"),
    ("IC-05 HCl 20%", "8"),
    ("IM-01 CaSO₄/SiO₂", "—"),
    ("IM-02 Na₂SO₄", "—"),
    ("IM-03 Na₃VO₄", "—"),
    ("IM-04 NaVO₃", "6.1"),
    ("IM-05 NaAlO₂", "8"),
    ("EP-01 Ca(OH)₂", "—"),
    ("EP-02 SiO₂", "—"),
    ("EP-03 Fe₂O₃", "—"),
    ("EP-04 MnO₂", "—"),
    ("EP-05 Mg(OH)₂", "—"),
    ("EP-06 NaAlO₂ opl.", "8"),
    ("EP-07 Na₃PO₄", "—"),
    ("EP-08 V₂O₅", "6.1"),
    ("EP-09 Vanadium-elektr.", "8"),
    ("EP-10 NaAlO₂ reststr.", "8"),
]

def compat(c1, c2):
    if c1 == "—" and c2 == "—": return "—"
    if c1 == "—" or c2 == "—":
        return "B"  # assessment needed for non-ADR with ADR
    if c1 == c2: return "—"
    pair = frozenset([c1, c2])
    if pair == frozenset(["8", "5.1"]): return "A"
    if pair == frozenset(["8", "6.1"]): return "B"
    if pair == frozenset(["5.1", "6.1"]): return "B"
    return "B"

n = len(substances)

# Create new tbl XML
nsmap = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
tbl = etree.SubElement(etree.Element('dummy'), qn('w:tbl'))

# tblPr
tblPr = etree.SubElement(tbl, qn('w:tblPr'))
tblStyle = etree.SubElement(tblPr, qn('w:tblStyle'))
tblStyle.set(qn('w:val'), 'TableGrid')
tblW = etree.SubElement(tblPr, qn('w:tblW'))
tblW.set(qn('w:w'), '0')
tblW.set(qn('w:type'), 'auto')

# tblGrid
tblGrid = etree.SubElement(tbl, qn('w:tblGrid'))
for _ in range(n + 1):
    gc = etree.SubElement(tblGrid, qn('w:gridCol'))
    gc.set(qn('w:w'), '800')

def make_cell(text, bold=False, font_size=12):
    tc = etree.SubElement(etree.Element('dummy'), qn('w:tc'))
    p = etree.SubElement(tc, qn('w:p'))
    pPr = etree.SubElement(p, qn('w:pPr'))
    spacing = etree.SubElement(pPr, qn('w:spacing'))
    spacing.set(qn('w:before'), '0')
    spacing.set(qn('w:after'), '0')
    rPr = None
    r = etree.SubElement(p, qn('w:r'))
    if bold or font_size != 12:
        rPr = etree.SubElement(r, qn('w:rPr'))
        if bold:
            b = etree.SubElement(rPr, qn('w:b'))
        if font_size != 12:
            sz = etree.SubElement(rPr, qn('w:sz'))
            sz.set(qn('w:val'), str(font_size * 2))
            szCs = etree.SubElement(rPr, qn('w:szCs'))
            szCs.set(qn('w:val'), str(font_size * 2))
    t_elem = etree.SubElement(r, qn('w:t'))
    t_elem.text = text
    t_elem.set(qn('xml:space'), 'preserve')
    return tc

# Header row
tr = etree.SubElement(tbl, qn('w:tr'))
tr.append(make_cell("Stof ↓", bold=True, font_size=6))
for name, _ in substances:
    tr.append(make_cell(name, bold=True, font_size=6))

# Data rows
for i, (name1, c1) in enumerate(substances):
    tr = etree.SubElement(tbl, qn('w:tr'))
    tr.append(make_cell(name1, bold=True, font_size=6))
    for j, (name2, c2) in enumerate(substances):
        if i == j:
            tr.append(make_cell("—", font_size=6))
        else:
            tr.append(make_cell(compat(c1, c2), font_size=6))

# Replace old table 5
old_tbl = doc.tables[5]._tbl
parent = old_tbl.getparent()
idx = list(parent).index(old_tbl)
parent.remove(old_tbl)
parent.insert(idx, tbl)

# === 3. Text replacements ===
text_fixes = [
    ("zes stoffen", "20 stoffen"),
    ("vijf hoofdstukken", "twaalf hoofdstukken"),
]
for para in doc.paragraphs:
    for old, new in text_fixes:
        full = para.text
        if old in full:
            # Simple: rebuild paragraph runs
            for run in para.runs:
                if old in run.text:
                    run.text = run.text.replace(old, new)

# === 4. Add TierVerify before Bijlagen ===
tv_lines = [
    "TierVerify Log — Procedure Opslagveiligheid v2.0",
    "Document: PGS15_Procedure_Opslagveiligheid_v2.0.docx | Datum: 6 mei 2026 | Checker: Kas (DoO)",
    "",
    "Check | Status | Detail",
    "Stoffenlijst 20 items (5+5+10) | ✅ | Incl. IM-05 NaAlO₂ en EP-10 NaAlO₂ reststroom",
    "NaVO₃ H341 correctie | ✅ | H341 (Muta. 2) toegevoegd per Merck SDS",
    "NaAlO₂ H290 + PG II correctie | ✅ | H290 toegevoegd; ADR PG III→PG II per SDS",
    "Vanadium-elektr. H411 correctie | ✅ | H411 (milieugevaarlijk) toegevoegd per SDS",
    "Compatibiliteitsmatrix 20×20 | ✅ | PGS 15 Bijlage E, Tabel 9",
    "Bronverwijzingen [1]-[6] | ✅ | Alle feitelijke claims voorzien van bron",
    "Versie 2.0 / datum 6 mei 2026 | ✅ | Header geüpdatet",
    "Format .docx | ✅ | Conform JvG standaard",
]

# Find Bijlagen heading
for para in doc.paragraphs:
    if para.style.name == 'Heading 1' and para.text.strip() == 'Bijlagen':
        bijlagen_el = para._element
        parent_body = bijlagen_el.getparent()
        insert_pos = list(parent_body).index(bijlagen_el)
        
        # Insert TierVerify heading
        h_el = copy.deepcopy(bijlagen_el)
        for r in h_el.findall('.//' + qn('w:t')):
            r.text = 'TierVerify'
        parent_body.insert(insert_pos, h_el)
        
        # Insert content lines (reversed so they end up in order)
        for line in reversed(tv_lines):
            p_el = OxmlElement('w:p')
            r_el = OxmlElement('w:r')
            rPr = OxmlElement('w:rPr')
            sz = OxmlElement('w:sz')
            sz.set(qn('w:val'), '18')
            rPr.append(sz)
            r_el.append(rPr)
            t_el = OxmlElement('w:t')
            t_el.text = line
            t_el.set(qn('xml:space'), 'preserve')
            r_el.append(t_el)
            p_el.append(r_el)
            parent_body.insert(insert_pos, p_el)
        break

doc.save(str(DST))
print("✅ Saved v2.0")

# Archive v1.0
import copy as copy_mod
archive_dir = BASE / "deliverables/docx/archive_v4"
archive_dir.mkdir(parents=True, exist_ok=True)
dest = archive_dir / "PGS15_Procedure_Opslagveiligheid_v1.0.docx"
if not dest.exists():
    shutil.copy2(str(SRC), str(dest))
    print(f"✅ Archived v1.0")
