#!/usr/bin/env python3
"""
PGS-15 Phoenix Metals — Volledige v6.1 correctie (ronde 2)
De sub-agent heeft structuur behouden maar te weinig content correcties.
Dit script vult de ontbrekende correcties aan.
"""
from docx import Document
import os, re, copy

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

def replace_in_paragraph(paragraph, old, new):
    """Replace text in paragraph preserving run formatting."""
    full = paragraph.text
    if old not in full:
        return False
    
    # Try run-level replacement first
    for run in paragraph.runs:
        if old in run.text:
            run.text = run.text.replace(old, new)
            return True
    
    # If text spans multiple runs, rebuild
    new_text = full.replace(old, new)
    if len(paragraph.runs) > 0:
        paragraph.runs[0].text = new_text
        for run in paragraph.runs[1:]:
            run.text = ''
        return True
    return False

def process_doc(filename, corrections):
    """Apply corrections to a DOCX file."""
    global total_changes
    fp = os.path.join(BASE, filename)
    if not os.path.exists(fp):
        print(f"  ⚠️ Niet gevonden: {fp}")
        return
    
    doc = Document(fp)
    changes = 0
    
    for i, p in enumerate(doc.paragraphs):
        for old, new in corrections:
            if old in p.text:
                if replace_in_paragraph(p, old, new):
                    changes += 1
    
    # Also check tables
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for p in cell.paragraphs:
                    for old, new in corrections:
                        if old in p.text:
                            if replace_in_paragraph(p, old, new):
                                changes += 1
    
    doc.save(fp)
    total_changes += changes
    print(f"  ✅ {filename}: {changes} correcties")

# ═══════════════════════════════════════════════════════════════
# UNIVERSELE CORRECTIES (voor ALLE documenten)
# ═══════════════════════════════════════════════════════════════

universal = [
    # Versie referenties
    ('Versie 5.0', 'Versie 6.1'),
    ('versie 5.0', 'versie 6.1'),
    ('Meta-Dossier Pilot Plant Slag Chemicals v5.0', 'Meta-Dossier Pilot Plant Slag Chemicals v6.1'),
    ('Chemicals Master Register v2.1.0', 'Chemicals Master Register v6.1'),
    ('PM-HSE-FORM-AUD-005', 'PM-HSE-FORM-AUD-005'),
    # 20 stoffen → 18 stoffen (voorzichtig, alleen waar relevant)
]

# ═══════════════════════════════════════════════════════════════
# DOCUMENT-SPECIFIEKE CORRECTIES
# ═══════════════════════════════════════════════════════════════

print("="*70)
print("RONDE 2 — PGS-15 Phoenix Metals v6.1 Correcties")
print("="*70)

# ── D1 Kennisdossier ──
print("\n📄 D1 Kennisdossier")
process_doc('PGS15_Kennisdossier_Phoenix_Metals_D1_v6.1.docx', [
    ('H₂SO₄: ~118 kg (drempel 1.000 ton)', 'H₂SO₄: 150 kg (drempel 1.000 ton)'),
    ('H₂O₂: ~44 kg (drempel 50 ton)', 'H₂O₂: 150 kg (drempel 50 ton)'),
    ('V₂O₅: <1 kg (geen specifieke drempel)', 'V₂O₅: 150 kg (drempel 5 ton)'),
    ('Totaal: <500 kg (drempel 50-200 ton)', 'Totaal: 2.700 kg (18 × 150 kg, drempel 50-200 ton)'),
    ('→ BRZO ni', '→ BRZO niet van toepassing (< drempelwaarden per categorie)'),
    ('SDS-data voor 20 stoffen', 'SDS-data voor 18 stoffen'),
    ('stoffenlijst met SDS-data voor 20 stoffen', 'stoffenlijst met SDS-data voor 18 stoffen'),
    *universal,
])

# ── D2 Veilig Werken ──
print("\n📄 D2 Veilig Werken")
process_doc('PGS15_VeiligWerken_HSEQ_Phoenix_Metals_D2_v6.1.docx', [
    ('stoffenbestand van 8 naar 20 stoffen', 'stoffenbestand van 8 naar 18 stoffen'),
    ('Toevoeging 12 nieuwe stoffen', 'Toevoeging 10 nieuwe stoffen'),
    ('Meta-Dossier Pilot Plant Slag Chemicals v5.0', 'Meta-Dossier Pilot Plant Slag Chemicals v6.1'),
    ('v5.0 (7 mei 2026): Update stoffenbestand van 8 naar 20 stoffen', 
     'v6.1 (7 mei 2026): Norm-correctie PGS 15:2025 — voetnoot c, ADR-route leidend'),
    *universal,
])

# ── D3 Veiligheidsinfo ──
print("\n📄 D3 Veiligheidsinfo")
process_doc('PGS15_Veiligheidsinfo_Documentatie_Phoenix_Metals_D3_v6.1.docx', [
    ('alle 20 stoffen', 'alle 18 stoffen'),
    ('20 stoffen die binnen de Pilot Plant aanwezig zijn: 5 input chemical', 
     '18 stoffen die binnen de Pilot Plant aanwezig zijn: 5 input chemical'),
    *universal,
])

# ── D4 Opslagveiligheid ──
print("\n📄 D4 Opslagveiligheid")
process_doc('PGS15_MasterSOP_Opslagveiligheid_Phoenix_Metals_D4_v6.1.docx', [
    ('Kernregels voor Phoenix Metals (20 stoffen, 3 opslagvakken)', 
     'Kernregels voor Phoenix Metals (18 stoffen, 3 opslagvakken)'),
    ('Meta-Dossier Pilot Plant Slag Chemicals v5.0', 'Meta-Dossier Pilot Plant Slag Chemicals v6.1'),
    ('Stoffenlijst compleet (20 stoffen)', 'Stoffenlijst compleet (18 stoffen)'),
    ('Segregatiematrix 20 stoffen', 'Segregatiematrix 18 stoffen'),
    ('Meta-Dossier v5.0', 'Meta-Dossier v6.1'),
    *universal,
])

# ── Basishandleiding ──
print("\n📄 Basishandleiding")
process_doc('PGS15_Basishandleiding_Phoenix_Metals_v6.1.docx', [
    ('Bijgewerkt voor 20 stoffen', 'Bijgewerkt voor 18 stoffen'),
    ('Versie 5.0 — Bijgewerkt voor 20 stoffen', 'Versie 6.1 — Bijgewerkt voor 18 stoffen'),
    ('uitgebreid van 8 naar 20 stoffen', 'uitgebreid van 8 naar 18 stoffen'),
    ('volledige update ten opzichte van v4.0', 'norm-correctie PGS 15:2025 t.o.v. v5.0'),
    *universal,
])

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

# ── Audit Checklist ──
print("\n📄 Audit Checklist")
process_doc('PGS15_Audit_Checklist_v6.1.docx', [
    ('20 stoffen verwerkt (5 input, 5 intermediair, 10 eindproduct)', 
     '18 stoffen verwerkt (5 input, 5 intermediair, 8 eindproduct)'),
    ('Phoenix Metals v5.0', 'Phoenix Metals v6.1'),
    *universal,
])

# ── Audit Procedure ──
print("\n📄 Audit Procedure")
process_doc('PGS15_Audit_Procedure_v6.1.docx', [
    ('Audit Checklist v5.0', 'Audit Checklist v6.1'),
    ('Audit Procedure v5.0', 'Audit Procedure v6.1'),
    ('Aanvullend: seperate document: Audit Checklist v4.0', 'Zie: Audit Checklist v6.1'),
    *universal,
])

# ── Audit Rapport Template ──
print("\n📄 Audit Rapport Template")
process_doc('PGS15_Audit_Rapport_Template_v6.1.docx', [
    ('Stoffeninventarisatie (20 stoffen)', 'Stoffeninventarisatie (18 stoffen)'),
    ('Audit Checklist v5.0 en Audit Procedure v5.0', 'Audit Checklist v6.1 en Audit Procedure v6.1'),
    ('In v4.0 werd alleen klass', 'In eerdere versies werd alleen klass'),
    *universal,
])

# ── Procedure Opslagveiligheid ──
print("\n📄 Procedure Opslagveiligheid")
process_doc('PGS15_Procedure_Opslagveiligheid_v6.1.docx', [
    ('tussen de 20 stoffen', 'tussen de 18 stoffen'),
    ('TierVerify Log — Procedure Opslagveiligheid v2.0', 'TierVerify Log — Procedure Opslagveiligheid v6.1'),
    ('geschat volume', 'geschat volume'),  # this is fine, it's about emergency procedure
    *universal,
])

# ── Werkinstructie ──
print("\n📄 Werkinstructie")
process_doc('PGS15_Werkinstructie_GevaarlijkeStoffen_v6.1.docx', [
    *universal,
])

# ── Compliance Toetsing (handmatige versie — extra fix) ──
print("\n📄 Compliance Toetsing (handmatig)")
process_doc('PGS15_Compliance_Toetsing_Phoenix_Metals_v6.1.docx', [
    ('20 stoffen', '18 stoffen'),
    ('via de CMR-route: Muta. 2 (H341) + Repr. 2 (H361fd). ADR klasse 6.1 PG III.',
     'via ADR 6.1 PG III (<10.000 kg, PGS 15:2025 Tabel 6). CMR: Muta. 2 (H341) + Repr. 2 (H361fd) vereist arbo-maatregelen.'),
    ('Meta-Dossier v5.0', 'Meta-Dossier v6.1'),
    *universal,
])

# ── Compliance Toetsing Scanner ──
print("\n📄 Compliance Toetsing Scanner")
process_doc('PGS15_Compliance_Toetsing_Scanner_Phoenix_Metals_v6.1.docx', [
    ('alle 20 stoffen', 'alle 18 stoffen'),
    ('Versie 5.0 was de eerste complete toetsing voor de Pilot Plant met alle 20 stoffen.',
     'Versie 5.0 was de eerste complete toetsing. V6.1: PGS 15:2025 norm-gecorrigeerd (voetnoot c, ADR-route leidend).'),
    *universal,
])

print(f"\n{'='*70}")
print(f"TOTAAL: {total_changes} correcties toegepast")
print(f"{'='*70}")
