#!/usr/bin/env python3
"""Her-Audit PGS 15 Documenten — Post-Fix Verificatie"""

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

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

FILES = [
    "PGS15_Kennisdossier_Phoenix_Metals_D1_v5.0.docx",
    "PGS15_VeiligWerken_HSEQ_Phoenix_Metals_D2_v5.0.docx",
    "PGS15_Veiligheidsinfo_Documentatie_Phoenix_Metals_D3_v5.0.docx",
    "PGS15_MasterSOP_Opslagveiligheid_Phoenix_Metals_D4_v5.0.docx",
    "PGS15_Management_Presentatie_Phoenix_Metals_D5_v5.0.pptx",
    "PGS15_Audit_Checklist_v5.0.docx",
    "PGS15_Audit_Procedure_v5.0.docx",
    "PGS15_Audit_Rapport_Template_v5.0.docx",
    "PGS15_Compliance_Toetsing_Phoenix_Metals_v5.0.docx",
    "PGS15_Basishandleiding_Phoenix_Metals_v5.0.docx",
    "PGS15_Werkinstructie_GevaarlijkeStoffen_v2.0.docx",
    "PGS15_Procedure_Opslagveiligheid_v2.0.docx",
    "PGS15_Beleidsdocument_Policy_v3.0.docx",
]

def extract_text_docx(path):
    texts = []
    doc = Document(path)
    for p in doc.paragraphs:
        texts.append(p.text)
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                texts.append(cell.text)
    # Also check headers/footers
    for section in doc.sections:
        for p in section.header.paragraphs:
            texts.append(p.text)
        for p in section.footer.paragraphs:
            texts.append(p.text)
        for t in section.header.tables:
            for row in t.rows:
                for cell in row.cells:
                    texts.append(cell.text)
        for t in section.footer.tables:
            for row in t.rows:
                for cell in row.cells:
                    texts.append(cell.text)
    return "\n".join(texts)

def extract_text_pptx(path):
    texts = []
    prs = Presentation(path)
    for slide in prs.slides:
        for shape in slide.shapes:
            if shape.has_text_frame:
                for p in shape.text_frame.paragraphs:
                    texts.append(p.text)
            if shape.has_table:
                for row in shape.table.rows:
                    for cell in row.cells:
                        texts.append(cell.text)
    return "\n".join(texts)

def audit_file(filepath):
    if not os.path.exists(filepath):
        return {"exists": False}
    
    ext = os.path.splitext(filepath)[1].lower()
    if ext == ".pptx":
        text = extract_text_pptx(filepath)
    else:
        text = extract_text_docx(filepath)
    
    text_lower = text.lower()
    
    # 1. Oude stofnamen
    naoh = len(re.findall(r'\bnaoh\b', text_lower))
    al_sulfaat = len(re.findall(r'aluminiumsulfaat', text_lower))
    cao = len(re.findall(r'calciumoxide', text_lower))
    saru = len(re.findall(r'saru[- ]ash|(?<!\w)saru(?!\w)', text_lower))
    # exclude "desinfectans" context - SARU as standalone
    saru = len(re.findall(r'saru', text_lower))
    # check if SARU appears outside "desinfectans" context
    saru_standalone = 0
    for m in re.finditer(r'saru', text_lower):
        start = max(0, m.start()-20)
        context = text_lower[start:m.end()+20]
        if 'desinfectan' not in context:
            saru_standalone += 1
    
    # 2. Correcties
    h341 = "H341" in text
    h290 = "H290" in text
    h411 = "H411" in text
    
    # 3. TierVerify
    tier_verify = bool(re.search(r'TierVerify|GEVERIFIËERD|geverifieerd', text, re.IGNORECASE))
    
    # 4. 20 stoffen
    twintig_stoffen = len(re.findall(r'20 stoffen|twintig stoffen', text_lower))
    # Check "8 stoffen" as total (not "ADR-klasse 8 stoffen" or "klasse 8")
    acht_stoffen_fout = 0
    for m in re.finditer(r'8 stoffen', text_lower):
        start = max(0, m.start()-30)
        context = text_lower[start:m.end()]
        if 'klasse' not in context and 'adr' not in context:
            acht_stoffen_fout += 1
    
    # 5. Datum
    datum_ok = bool(re.search(r'6 mei 2026|06-05-2026|6 mei 2026', text))
    
    return {
        "exists": True,
        "naoh": naoh,
        "al_sulfaat": al_sulfaat,
        "cao": cao,
        "saru": saru_standalone,
        "h341": h341,
        "h290": h290,
        "h411": h411,
        "tier_verify": tier_verify,
        "twintig_stoffen": twintig_stoffen,
        "acht_stoffen_fout": acht_stoffen_fout,
        "datum_ok": datum_ok,
    }

labels = ["D1","D2","D3","D4","D5","D6","D7","D8","D9","D10","D11","D12","D13"]

print("## Her-Audit Resultaat — Alle 13 Documenten\n")
print("| # | Document | NaOH | Al-sulfaat | CaO | SARU | H341 | H290 | H411 | TierVerify | 20 stoffen | Datum OK | OORDEEL |")
print("|---|----------|------|------------|-----|------|------|------|------|------------|------------|----------|---------|")

failures = []
for i, (f, label) in enumerate(zip(FILES, labels), 1):
    path = os.path.join(BASE, f)
    r = audit_file(path)
    
    if not r["exists"]:
        print(f"| {i} | {label} | ❌ BESTAND ONTBREEKT | | | | | | | | | | ❌ FAIL |")
        failures.append(f"{label}: Bestand ontbreekt — {f}")
        continue
    
    # Determine pass/fail
    old_names = r["naoh"] + r["al_sulfaat"] + r["cao"] + r["saru"]
    
    naoh_s = str(r["naoh"]) if r["naoh"] == 0 else f"❌ {r['naoh']}"
    al_s = str(r["al_sulfaat"]) if r["al_sulfaat"] == 0 else f"❌ {r['al_sulfaat']}"
    cao_s = str(r["cao"]) if r["cao"] == 0 else f"❌ {r['cao']}"
    saru_s = str(r["saru"]) if r["saru"] == 0 else f"❌ {r['saru']}"
    
    h341_s = "✅" if r["h341"] else "❌"
    h290_s = "✅" if r["h290"] else "❌"
    h411_s = "✅" if r["h411"] else "❌"
    tv_s = "✅" if r["tier_verify"] else "❌"
    
    twintig_s = "✅" if r["twintig_stoffen"] > 0 else "➖"
    if r["acht_stoffen_fout"] > 0:
        twintig_s = f"❌ 8-stoffen ({r['acht_stoffen_fout']})"
    
    datum_s = "✅" if r["datum_ok"] else "❌"
    
    # Verdict
    fails = []
    if r["naoh"] > 0: fails.append(f"NaOH:{r['naoh']}")
    if r["al_sulfaat"] > 0: fails.append(f"Al-sulfaat:{r['al_sulfaat']}")
    if r["cao"] > 0: fails.append(f"CaO:{r['cao']}")
    if r["saru"] > 0: fails.append(f"SARU:{r['saru']}")
    if not r["h341"]: fails.append("H341 ontbreekt")
    if not r["h290"]: fails.append("H290 ontbreekt")
    if not r["h411"]: fails.append("H411 ontbreekt")
    if not r["tier_verify"]: fails.append("TierVerify ontbreekt")
    if r["acht_stoffen_fout"] > 0: fails.append(f"8 stoffen als totaal:{r['acht_stoffen_fout']}")
    
    verdict = "✅ PASS" if not fails else "❌ FAIL"
    
    print(f"| {i} | {label} | {naoh_s} | {al_s} | {cao_s} | {saru_s} | {h341_s} | {h290_s} | {h411_s} | {tv_s} | {twintig_s} | {datum_s} | {verdict} |")
    
    if fails:
        failures.append(f"{label}: {', '.join(fails)}")

print()
if failures:
    print("### ❌ GEFALLEN DOCUMENTEN:")
    for f in failures:
        print(f"- {f}")
else:
    print("### ✅ ALLE 13 DOCUMENTEN GESLAAGD")
