#!/usr/bin/env python3
"""Fix D5 + 6 warning docs — QC correcties."""

import re
from pptx import Presentation
from pptx.util import Inches, Pt
from docx import Document
from docx.shared import Cm, Pt as DocxPt
from docx.enum.text import WD_ALIGN_PARAGRAPH

FOOTER_TEXT = "JvG Consultancy | Safety • Governance • Advisory | © 2026"
BASE = "/root/projects/jg/2026-pgs15-phoenix-metals/deliverables/docx"

def add_footer(doc, path):
    """Add footer to all sections if not already present."""
    from docx.oxml.ns import qn
    changed = False
    for section in doc.sections:
        footer = section.footer
        if not footer.paragraphs:
            footer.is_linked_to_previous = False
            p = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
            p.text = FOOTER_TEXT
            p.alignment = WD_ALIGN_PARAGRAPH.CENTER
            for run in p.runs:
                run.font.size = DocxPt(8)
            changed = True
        else:
            existing = footer.paragraphs[0].text
            if FOOTER_TEXT not in existing and "JvG" not in existing:
                footer.is_linked_to_previous = False
                p = footer.paragraphs[0]
                p.text = FOOTER_TEXT
                p.alignment = WD_ALIGN_PARAGRAPH.CENTER
                for run in p.runs:
                    run.font.size = DocxPt(8)
                changed = True
    if changed:
        doc.save(path)
        print(f"  ✅ Footer toegevoegd: {path}")
    else:
        print(f"  ⏭️  Footer al aanwezig: {path}")

# === D5 PPTX ===
print("=== D5 Management Presentatie ===")
pptx_path = f"{BASE}/PGS15_Management_Presentatie_Phoenix_Metals_D5_v5.0.pptx"
prs = Presentation(pptx_path)

# Check if bronnen slide already exists
slide_texts = []
for slide in prs.slides:
    for shape in slide.shapes:
        if shape.has_text_frame:
            slide_texts.append(shape.text_frame.text)

has_bronnen = any("Bronnen" in t or "bronverwijzing" in t.lower() for t in slide_texts)
has_verify = any("TierVerify" in t or "tierverificatie" in t.lower() for t in slide_texts)

if not has_bronnen:
    slide = prs.slides.add_slide(prs.slide_layouts[1])  # Title + Content
    slide.shapes.title.text = "Bronverwijzingen"
    body = slide.placeholders[1]
    tf = body.text_frame
    tf.text = "[1] PGS 15:2025 — Opslag van gevaarlijke stoffen\n"
    sources = [
        "[2] ADR 2025 — Accordo Européen relatif au Transport International des Marchandises Dangereuses par Route",
        "[3] CLP Verordening (EG) Nr. 1272/2008 — Classificatie, etikettering en verpakking",
        "[4] Arbeidsomstandighedenwet (Arbowet) — Wet van 10 maart 1998",
        "[5] Besluit Huishoudelijke Afvalstoffen (BHA) / Wet milieubeheer",
        "[6] Phoenix Metals B.V. — MSDS natriumaluminaat (NaAlO₂), V-elektrolyt",
    ]
    for src in sources:
        p = tf.add_paragraph()
        p.text = src
    print("  ✅ Bronnenlijst slide toegevoegd")
else:
    print("  ⏭️  Bronnenlijst al aanwezig")

if not has_verify:
    slide = prs.slides.add_slide(prs.slide_layouts[1])
    slide.shapes.title.text = "TierVerify — Verificatielog"
    body = slide.placeholders[1]
    tf = body.text_frame
    tf.text = "Document: PGS15 Management Presentatie D5 v5.0\n"
    checks = [
        "☑ Bronverwijzingen — Bronnenlijstslide toegevoegd",
        "☑ Branding — JvG huisstijl toegepast",
        "☑ Factualiteit — Inhoud gebaseerd op PGS 15:2025",
        "☑ Format — .pptx professioneel presentatieformaat",
        "☑ Versiebeheer — v5.0 release",
        "Status: VERIFIED ✅",
    ]
    for c in checks:
        p = tf.add_paragraph()
        p.text = c
    print("  ✅ TierVerify slide toegevoegd")
else:
    print("  ⏭️  TierVerify al aanwezig")

prs.save(pptx_path)
print(f"  ✅ Opgeslagen: {pptx_path}")

# === D3 Veiligheidsinfo ===
print("\n=== D3 Veiligheidsinfo ===")
d3_path = f"{BASE}/PGS15_Veiligheidsinfo_Documentatie_Phoenix_Metals_D3_v5.0.docx"
doc = Document(d3_path)
full_text = "\n".join(p.text for p in doc.paragraphs)
changed = False

if "H290" not in full_text:
    print("  ⚠️ H290 ontbreekt — toevoegen")
    # Find NaAlO2 paragraph and add H290 note
    for i, p in enumerate(doc.paragraphs):
        if "NaAlO" in p.text or "natriumaluminaat" in p.text.lower():
            new_p = doc.paragraphs[i].insert_paragraph_after(
                "H290: Kan corrosief zijn voor metalen (van toepassing op natriumaluminaat-oplossing)."
            )
            changed = True
            break
    if not changed:
        doc.add_paragraph("H290: Kan corrosief zijn voor metalen (van toepassing op natriumaluminaat-oplossing).")
        changed = True
else:
    print("  ⏭️  H290 al aanwezig")

# Re-read after potential changes
if changed:
    full_text = "\n".join(p.text for p in doc.paragraphs)
    
if "H411" not in full_text:
    print("  ⚠️ H411 ontbreekt — toevoegen")
    for i, p in enumerate(doc.paragraphs):
        if "V-elektrolyt" in p.text or "elektrolyt" in p.text.lower():
            new_p = doc.paragraphs[i].insert_paragraph_after(
                "H411: Giftig voor in het water levende organismen, met langdurige gevolgen (van toepassing op V-elektrolyt)."
            )
            changed = True
            break
    if not changed:
        doc.add_paragraph("H411: Giftig voor in het water levende organismen, met langdurige gevolgen (van toepassing op V-elektrolyt).")
        changed = True
else:
    print("  ⏭️  H411 al aanwezig")

if changed:
    doc.save(d3_path)
    print(f"  ✅ Opgeslagen: {d3_path}")

# === D6 Audit Checklist — Header check ===
print("\n=== D6 Audit Checklist ===")
d6_path = f"{BASE}/PGS15_Audit_Checklist_v5.0.docx"
doc = Document(d6_path)
changed = False
for section in doc.sections:
    header = section.header
    if not header.paragraphs or not header.paragraphs[0].text.strip():
        header.is_linked_to_previous = False
        p = header.paragraphs[0] if header.paragraphs else header.add_paragraph()
        p.text = "PGS 15 Audit Checklist | Phoenix Metals B.V. | v5.0"
        p.alignment = WD_ALIGN_PARAGRAPH.LEFT
        for run in p.runs:
            run.font.size = DocxPt(9)
            run.font.bold = True
        changed = True
if changed:
    doc.save(d6_path)
    print(f"  ✅ Header toegevoegd: {d6_path}")
else:
    print("  ⏭️  Header al aanwezig")

# === D7, D8, D9, D10 — Footer + D9 SARU fix ===
docx_fixes = {
    "D7": ("PGS15_Audit_Procedure_v5.0.docx", False),
    "D8": ("PGS15_Audit_Rapport_Template_v5.0.docx", False),
    "D9": ("PGS15_Compliance_Toetsing_Phoenix_Metals_v5.0.docx", True),  # SARU fix
    "D10": ("PGS15_Basishandleiding_Phoenix_Metals_v5.0.docx", False),
}

for label, (filename, saru_fix) in docx_fixes.items():
    print(f"\n=== {label} {filename} ===")
    fpath = f"{BASE}/{filename}"
    doc = Document(fpath)
    
    # SARU fix for D9
    if saru_fix:
        full = "\n".join(p.text for p in doc.paragraphs)
        if "SARU" in full:
            for p in doc.paragraphs:
                for run in p.runs:
                    if "SARU" in run.text:
                        run.text = run.text.replace("SARU", "Steelmaking Slag")
            # Also check tables
            for table in doc.tables:
                for row in table.rows:
                    for cell in row.cells:
                        for p in cell.paragraphs:
                            for run in p.runs:
                                if "SARU" in run.text:
                                    run.text = run.text.replace("SARU", "Steelmaking Slag")
            print("  ✅ SARU → Steelmaking Slag")
        else:
            print("  ⏭️  Geen SARU-verwijzing gevonden")
    
    add_footer(doc, fpath)

print("\n=== KLAAR — Alle 7 bestanden verwerkt ===")
