#!/usr/bin/env python3
"""Fix QC remaining issues in 6 PGS-15 v6.1 documents."""

import os, re
from docx import Document
from pptx import Presentation

BASE = "/root/projects/jg/2026-pgs15-phoenix-metals/deliverables/docx"

def replace_in_runs(runs, replacements):
    """Replace text across runs, merging if needed."""
    full = ''.join(r.text for r in runs)
    changed = False
    for old, new in replacements:
        if old in full:
            full = full.replace(old, new)
            changed = True
    if changed and runs:
        runs[0].text = full
        for r in runs[1:]:
            r.text = ''
    return changed

def fix_docx(filepath, replacements):
    doc = Document(filepath)
    count = 0
    for para in doc.paragraphs:
        if replace_in_runs(para.runs, replacements):
            count += 1
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for para in cell.paragraphs:
                    if replace_in_runs(para.runs, replacements):
                        count += 1
    doc.save(filepath)
    return count

def fix_pptx(filepath, replacements):
    prs = Presentation(filepath)
    count = 0
    for slide in prs.slides:
        for shape in slide.shapes:
            if shape.has_text_frame:
                for para in shape.text_frame.paragraphs:
                    if replace_in_runs(para.runs, replacements):
                        count += 1
            if shape.has_table:
                for row in shape.table.rows:
                    for cell in row.cells:
                        for para in cell.text_frame.paragraphs:
                            if replace_in_runs(para.runs, replacements):
                                count += 1
    prs.save(filepath)
    return count

# Define replacements per document
docs = [
    ("PGS15_Management_Presentatie_Phoenix_Metals_D5_v6.1.pptx", "pptx", [
        ("v5.0", "v6.1"),
        ("20 stoffen", "18 stoffen"),
    ]),
    ("PGS15_Beleidsdocument_Policy_v6.1.docx", "docx", [
        ("3.0", "6.1"),
    ]),
    ("PGS15_Audit_Rapport_Template_v6.1.docx", "docx", [
        ("Rapportversie: 5.0", "Rapportversie: 6.1"),
        ("Versie 5.0", "Versie 6.1"),
        ("v5.0", "v6.1"),
    ]),
    ("PGS15_Kennisdossier_Phoenix_Metals_D1_v6.1.docx", "docx", [
        ("5.0", "6.1"),
    ]),
    ("PGS15_VeiligWerken_HSEQ_Phoenix_Metals_D2_v6.1.docx", "docx", [
        ("20 geregistreerde stoffen", "18 geregistreerde stoffen"),
        ("20 geregistreerd", "18 geregistreerd"),
    ]),
    ("PGS15_Procedure_Opslagveiligheid_v6.1.docx", "docx", [
        ("2.0", "6.1"),
    ]),
]

print("=== FIXING DOCUMENTS ===\n")
for fname, ftype, reps in docs:
    path = os.path.join(BASE, fname)
    if not os.path.exists(path):
        print(f"❌ MISSING: {fname}")
        continue
    if ftype == "pptx":
        n = fix_pptx(path, reps)
    else:
        n = fix_docx(path, reps)
    print(f"✅ {fname}: {n} fixes applied")

# VERIFICATION
print("\n=== VERIFICATION ===\n")
search_terms = ["v5.0", "v3.0", "v2.0", "20 stoffen", "20 geregistreerd", "Rapportversie: 5.0", "Versie 5.0", "Versie 3.0", "Versie 2.0"]
all_clean = True

for fname, ftype, _ in docs:
    path = os.path.join(BASE, fname)
    if not os.path.exists(path):
        continue
    
    if ftype == "pptx":
        prs = Presentation(path)
        texts = []
        for slide in prs.slides:
            for shape in slide.shapes:
                if shape.has_text_frame:
                    for para in shape.text_frame.paragraphs:
                        texts.append(''.join(r.text for r in para.runs))
                if shape.has_table:
                    for row in shape.table.rows:
                        for cell in row.cells:
                            for para in cell.text_frame.paragraphs:
                                texts.append(''.join(r.text for r in para.runs))
    else:
        doc = Document(path)
        texts = []
        for para in doc.paragraphs:
            texts.append(para.text)
        for table in doc.tables:
            for row in table.rows:
                for cell in row.cells:
                    for para in cell.paragraphs:
                        texts.append(para.text)
    
    full_text = '\n'.join(texts)
    issues = []
    for term in search_terms:
        if term in full_text:
            issues.append(term)
    
    if issues:
        all_clean = False
        print(f"⚠️  {fname}: nog gevonden: {issues}")
    else:
        print(f"✅ {fname}: SCHOON")

print(f"\n{'✅ ALLES SCHOON' if all_clean else '⚠️  NOG ISSUES'}")
