#!/usr/bin/env python3
"""
Ronde 3 — Diepe correctie: paragraphs + tabellen + TierVerify
"""
from docx import Document
import os

BASE = '/root/projects/jg/2026-pgs15-phoenix-metals/deliverables/docx'
total = 0

def deep_replace(doc, replacements):
    """Replace in paragraphs AND table cells."""
    n = 0
    for p in doc.paragraphs:
        for old, new in replacements:
            if old in p.text:
                for run in p.runs:
                    if old in run.text:
                        run.text = run.text.replace(old, new)
                        n += 1
                # If text spans runs
                if old in p.text and n == 0:
                    full = p.text.replace(old, new)
                    if p.runs:
                        p.runs[0].text = full
                        for r in p.runs[1:]: r.text = ''
                        n += 1
    
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for p in cell.paragraphs:
                    for old, new in replacements:
                        if old in p.text:
                            for run in p.runs:
                                if old in run.text:
                                    run.text = run.text.replace(old, new)
                                    n += 1
                            if old in p.text and n == 0:
                                full = p.text.replace(old, new)
                                if p.runs:
                                    p.runs[0].text = full
                                    for r in p.runs[1:]: r.text = ''
                                    n += 1
    return n

def fix(name, reps):
    global total
    fp = os.path.join(BASE, name)
    if not os.path.exists(fp):
        print(f"  ⚠️ MISSING: {name}")
        return
    doc = Document(fp)
    n = deep_replace(doc, reps)
    doc.save(fp)
    total += n
    print(f"  ✅ {name}: {n} fixes")

# ═══ UNIVERSIELE REGELS ═══
U = [
    # Versies in headers/referenties
    ('Meta-Dossier Pilot Plant v5.0', 'Meta-Dossier Pilot Plant v6.1'),
    ('Meta-Dossier v5.0', 'Meta-Dossier v6.1'),
    ('Meta-Dossier Pilot Plant Slag Chemicals v5.0', 'Meta-Dossier Pilot Plant Slag Chemicals v6.1'),
    ('meta_dossier_pilot_plant_v5.0', 'meta_dossier_pilot_plant_v6.1'),
    ('SOP-PGS15-PM-D4-v5.0', 'SOP-PGS15-PM-D4-v6.1'),
    ('PGS15_Audit_Procedure_v5.0', 'PGS15_Audit_Procedure_v6.1'),
    ('PGS15_Procedure_Opslagveiligheid_v2.0', 'PGS15_Procedure_Opslagveiligheid_v6.1'),
    ('Rapport Template v5.0', 'Rapport Template v6.1'),
    ('Audit Checklist v5.0', 'Audit Checklist v6.1'),
    ('Audit Procedure v5.0', 'Audit Procedure v6.1'),
    ('PM-HSE-PROC-AUD-004 v4.0', 'PM-HSE-PROC-AUD-004 v6.1'),
    ('PM-HSE-TMPL-AUD-005', 'PM-HSE-TMPL-AUD-005'),
    ('Stoffenlijst v5.0', 'Stoffenlijst v6.1'),
    ('v5.0 (7 mei 2026): Update stoffenbestand van 8 naar 18 stoffen. Toevoeging 10 nieuwe stoffen',
     'v6.1 (7 mei 2026): PGS 15:2025 norm-correctie — voetnoot c, ADR-route leidend. 18 stoffen'),
    ('Versie 5.0 — Bijgewerkt', 'Versie 6.1 — Bijgewerkt'),
]

print("="*60)
print("RONDE 3 — Diepe correctie (paragraphs + tabellen)")
print("="*60)

# ── D1 Kennisdossier ──
print("\n📄 D1 Kennisdossier")
fix('PGS15_Kennisdossier_Phoenix_Metals_D1_v6.1.docx', [
    ('~100 L (~118 kg)', '150 L (150 kg)'),
    ('~118 kg', '150 kg'),
    ('~44 kg', '150 kg'),
    ('<500 kg totaal', '2.700 kg totaal (18 × 150 kg)'),
    ('Stoffenaantal: 8 → 20', 'Stoffenaantal: 8 → 18'),
    ('8 → 20 (ge', '8 → 18 (ge'),
    ('Stoffenregister actualiseren incl. 20 stoffen', 'Stoffenregister actualiseren incl. 18 stoffen'),
    ('Opslagplattegrond actualiseren met 20 stoffen', 'Opslagplattegrond actualiseren met 18 stoffen'),
    ('20 stoffen (SDS-geverifieerd)', '18 stoffen (SDS-geverifieerd)'),
    ('Update naar 20 stoffen', 'Update naar 18 stoffen'),
    ('TIERVERIFY — D1 Kennisdossier v5.0', 'TIERVERIFY — D1 Kennisdossier v6.1'),
    *U,
])

# ── D2 Veilig Werken ──
print("\n📄 D2 Veilig Werken")
fix('PGS15_VeiligWerken_HSEQ_Phoenix_Metals_D2_v6.1.docx', [
    ('20 stoffen geregistreerd', '18 stoffen geregistreerd'),
    ('TierVerify Log — 7 mei 2026 — Bron: Meta-Dossier v5.0', 'TierVerify Log — 7 mei 2026 — Bron: Meta-Dossier v6.1'),
    ('8 naar 18 stoffen', '8 naar 18 stoffen'),  # already correct
    *U,
])

# ── D3 Veiligheidsinfo ──
print("\n📄 D3 Veiligheidsinfo")
fix('PGS15_Veiligheidsinfo_Documentatie_Phoenix_Metals_D3_v6.1.docx', [
    ('20 stoffen (5 IC + 5 IM + 10 EP)', '18 stoffen (5 IC + 5 IM + 8 EP)'),
    ('20 stoffen', '18 stoffen'),
    *U,
])

# ── D4 Opslagveiligheid ──
print("\n📄 D4 Opslagveiligheid")
fix('PGS15_MasterSOP_Opslagveiligheid_Phoenix_Metals_D4_v6.1.docx', [
    ('Update 8→20 stoffen', 'Update 8→18 stoffen'),
    ('8→20 stoffen', '8→18 stoffen'),
    ('20 stoffen (SDS-geverifieerd)', '18 stoffen (SDS-geverifieerd)'),
    ('20 stoffen', '18 stoffen'),
    ('TIERVERIFY LOG — D4 v5.0', 'TIERVERIFY LOG — D4 v6.1'),
    ('v3.0, 01-2025', 'v1.0, 01-2025'),
    *U,
])

# ── Basishandleiding ──
print("\n📄 Basishandleiding")
fix('PGS15_Basishandleiding_Phoenix_Metals_v6.1.docx', [
    ('20 stoffen', '18 stoffen'),
    ('Alle 20 stoffen geverifieerd', 'Alle 18 stoffen geverifieerd'),
    ('uitgebreid van 8 naar 20', 'uitgebreid van 8 naar 18'),
    *U,
])

# ── Beleidsdocument ──
print("\n📄 Beleidsdocument")
fix('PGS15_Beleidsdocument_Policy_v6.1.docx', [
    ('20 stoffen', '18 stoffen'),
    *U,
])

# ── Audit Checklist ──
print("\n📄 Audit Checklist")
fix('PGS15_Audit_Checklist_v6.1.docx', [
    ('20 stoffen: 5 input, 5 intermediair, 10 eindproduct', '18 stoffen: 5 input, 5 intermediair, 8 eindproduct'),
    ('alle 20 stoffen', 'alle 18 stoffen'),
    ('20 stoffen', '18 stoffen'),
    ('Correcties v5.0 gedocumenteerd', 'Correcties v6.1 gedocumenteerd'),
    ('Correcties v5.0 geverifieerd', 'Correcties v6.1 geverifieerd'),
    ('Brondata — Meta-Dossier v5.0', 'Brondata — Meta-Dossier v6.1'),
    *U,
])

# ── Audit Procedure ──
print("\n📄 Audit Procedure")
fix('PGS15_Audit_Procedure_v6.1.docx', [
    ('inclusief alle 20 stoffen', 'inclusief alle 18 stoffen'),
    ('uitgebreid voor 20 stoffen', 'uitgebreid voor 18 stoffen'),
    ('bij 20 stoffen minimaal 50% steekproef (10 stoffen)', 'bij 18 stoffen minimaal 50% steekproef (9 stoffen)'),
    ('20 stoffen: zwavelzuur', '18 stoffen: zwavelzuur'),
    ('20 stoffen, 3 opslagvakken', '18 stoffen, 3 opslagvakken'),
    ('uitbreiding 8→20 stoffen', 'uitbreiding 8→18 stoffen'),
    ('Rapport Template v4.0', 'Rapport Template v6.1'),
    ('SDS\'en 20 stoffen', 'SDS\'en 18 stoffen'),
    *U,
])

# ── Audit Rapport Template ──
print("\n📄 Audit Rapport Template")
fix('PGS15_Audit_Rapport_Template_v6.1.docx', [
    ('20 stoffen, correcties verwerkt', '18 stoffen, correcties verwerkt'),
    ('20 stoffen', '18 stoffen'),
    ('Stoffenlijst v5.0', 'Stoffenlijst v6.1'),
    ('Audit Checklist v5.0', 'Audit Checklist v6.1'),
    ('In eerdere versies werd alleen klass', 'In eerdere versies werd alleen klass'),
    *U,
])

# ── Procedure Opslagveiligheid ──
print("\n📄 Procedure Opslagveiligheid")
fix('PGS15_Procedure_Opslagveiligheid_v6.1.docx', [
    ('20 stoffen', '18 stoffen'),
    *U,
])

# ── Compliance Toetsing ──
print("\n📄 Compliance Toetsing")
fix('PGS15_Compliance_Toetsing_Phoenix_Metals_v6.1.docx', [
    ('6.3 CMR-route', '6.3 CMR-toetsing (arbo-maatregelen, niet niveau-bepalend)'),
    *U,
])

# ── Compliance Toetsing Scanner ──
print("\n📄 Scanner Toetsing")
fix('PGS15_Compliance_Toetsing_Scanner_Phoenix_Metals_v6.1.docx', [
    ('Complete toetsing 20 stoffen', 'Complete toetsing 18 stoffen'),
    *U,
])

print(f"\n{'='*60}")
print(f"RONDE 3 TOTAAL: {total} correcties")
print(f"{'='*60}")
