#!/usr/bin/env python3
"""
Update PGS15 Compliance Toetsing v5.0 → v6.0
ALLEEN hoeveelheden en bijbehorende niveaus aanpassen naar 150 kg/ltr per product.
Structuur, opmaak, lay-out, inhoud blijven IDENTIEK aan v5.0.
"""
from docx import Document
from docx.shared import Pt, RGBColor
from copy import deepcopy
import shutil, os, datetime

SRC = '/root/.openclaw/media/inbound/PGS15_Compliance_Toetsing_Phoenix_Metals_v5.0---661ec953-b313-414e-96ed-87265b9f5471.docx'
DST = '/root/projects/jg/2026-pgs15-phoenix-metals/deliverables/docx/PGS15_Compliance_Toetsing_Phoenix_Metals_v6.0.docx'

# Archive existing v6.0
archive_dir = '/root/projects/jg/2026-pgs15-phoenix-metals/archive/'
os.makedirs(archive_dir, exist_ok=True)
if os.path.exists(DST):
    shutil.copy2(DST, os.path.join(archive_dir, 'PGS15_Compliance_Toetsing_Phoenix_Metals_v6.0_pre_150kg.docx'))

# Load v5.0 as base
doc = Document(SRC)

# ============================================================
# TEXT REPLACEMENTS — surgical, paragraph by paragraph
# ============================================================

changes = []

for i, p in enumerate(doc.paragraphs):
    text = p.text
    
    # 1. Title: update version number
    if 'v5.0' in text:
        for run in p.runs:
            if 'v5.0' in run.text:
                run.text = run.text.replace('v5.0', 'v6.0')
                changes.append(f"[{i}] Title version: v5.0 → v6.0")
    
    # 2. Paragraph 36: Sulfuric acid rationale — "<250 kg: Niveau B" stays correct for 150 kg
    # No change needed, already says <250 kg → B
    
    # 3. Paragraph 56: Na-metavanadate — "ondergrens 25 kg" stays, 150 kg > 25 kg → C stays
    # No change needed

    # 4. Paragraph 66: V2O5 — CMR route dominates, no quantity change needed
    # No change needed

    # 5. Paragraph 225: Klasse 8 aggregatie — update geschatte hoeveelheid
    if 'Totale geschatte hoeveelheid: >250 kg' in text:
        for run in p.runs:
            if 'Totale geschatte hoeveelheid: >250 kg' in run.text:
                run.text = run.text.replace(
                    'Totale geschatte hoeveelheid: >250 kg (ondergrens klasse 8 PG II). Aggregatie leidt tot Niveau C.',
                    'Totale hoeveelheid: 4 × 150 kg = 600 kg (boven ondergrens 250 kg klasse 8 PG II). Aggregatie leidt tot Niveau C.'
                )
                changes.append(f"[{i}] Aggregatie klasse 8: >250 kg geschat → 600 kg exact (4 × 150 kg)")
    
    # 6. Paragraph 229: CMR-route — no change needed (Niveau C ongeacht hoeveelheden)
    
    # 7. Paragraph 231: Seveso — update totalen
    if 'totale opslag < 5.000 kg' in text:
        for run in p.runs:
            if 'totale opslag < 5.000 kg' in run.text:
                run.text = run.text.replace(
                    'totale opslag < 5.000 kg',
                    'totale opslag 2.700 kg (18 × 150 kg) < 5.000 kg'
                )
                changes.append(f"[{i}] Seveso: < 5.000 kg → 2.700 kg exact")
    
    # 8. Paragraph 233: Catch-all check
    if 'geschat < 2.000 kg' in text:
        for run in p.runs:
            if 'geschat < 2.000 kg' in run.text:
                run.text = run.text.replace(
                    'Totale opslag Pilot Plant: geschat < 2.000 kg. Catch-all drempel: 1.000 kg. Indien > 1.000 kg: catch-all van toepassing.',
                    'Totale opslag Pilot Plant: 2.700 kg (18 × 150 kg). Catch-all drempel: 1.000 kg. Totaal > 1.000 kg → catch-all van toepassing.'
                )
                changes.append(f"[{i}] Catch-all: geschat <2.000 kg → exact 2.700 kg (boven 1.000 kg drempel)")
    
    # 9. Paragraph 235: Bvi
    if '< 1.000 kg individueel per stof' in text:
        for run in p.runs:
            if '< 1.000 kg individueel per stof' in run.text:
                run.text = run.text.replace(
                    'Bvi: Geen vergunningplicht (< 1.000 kg individueel per stof).',
                    'Bvi: Geen vergunningplicht (150 kg per stof < 1.000 kg drempel).'
                )
                changes.append(f"[{i}] Bvi: <1.000 kg → 150 kg per stof")

# ============================================================
# VERSION HISTORY — add v6.0 entry in the version table
# ============================================================

# Find version history table (Table 1)
for table in doc.tables:
    header = [cell.text.strip() for cell in table.rows[0].cells]
    if 'Versie' in header and 'Datum' in header and 'Wijziging' in header:
        # Add new row for v6.0
        new_row = table.add_row()
        cells = new_row.cells
        cells[0].text = '6.0'
        cells[1].text = '7 mei 2026'
        cells[2].text = 'Heranalyse met exact 150 kg/ltr per product (voorheen geschatte hoeveelheden). Alle niveaus herbevestigd: Niveau C blijft vereist (CMR-route). Aggregatie, Seveso en catch-all bijgewerkt naar exacte totalen.'
        for cell in cells:
            for para in cell.paragraphs:
                for run in para.runs:
                    run.font.name = 'Calibri'
                    run.font.size = Pt(11)
        changes.append("Versiehistorie: v6.0 entry toegevoegd")
        break

# ============================================================
# DOCUMENT HEADER — update version field
# ============================================================

for table in doc.tables:
    for row in table.rows:
        cells = row.cells
        if len(cells) >= 2:
            label = cells[0].text.strip()
            value = cells[1].text.strip()
            if label == 'Versie':
                cells[1].paragraphs[0].runs[0].text = '6.0'
                changes.append("Documentheader: Versie → 6.0")
            if label == 'Status':
                cells[1].paragraphs[0].runs[0].text = 'Definitief — 150 kg/ltr per product'
                changes.append("Documentheader: Status → Definitief — 150 kg/ltr")
            if label == 'Laatst bijgewerkt' or label == 'Datum':
                cells[1].paragraphs[0].runs[0].text = '7 mei 2026'
                changes.append("Documentheader: Datum → 7 mei 2026")

# ============================================================
# SAVE
# ============================================================

doc.save(DST)

print(f"✓ Document opgeslagen: {DST}")
print(f"✓ Aantal wijzigingen: {len(changes)}")
print("\nWijzigingen:")
for c in changes:
    print(f"  {c}")
