#!/usr/bin/env python3
"""PGS-15 Audit Toolkit — DOCX Generator v1.0
Generates 3 professional DOCX documents with JvG Consultancy huisstijl."""

import re
import os
from docx import Document
from docx.shared import Pt, Cm, RGBColor, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.section import WD_ORIENT
from docx.oxml.ns import qn, nsdecls
from docx.oxml import parse_xml

# === CONSTANTS ===
PRIMARY = RGBColor(0x00, 0x33, 0x66)
ACCENT = RGBColor(0x00, 0xA8, 0xE8)
BLACK = RGBColor(0x00, 0x00, 0x00)
WHITE = RGBColor(0xFF, 0xFF, 0xFF)
LIGHT_GRAY = RGBColor(0xF8, 0xF9, 0xFA)
BORDER_COLOR = RGBColor(0xE5, 0xE7, 0xEB)

FONT_BODY = 'Calibri'
SIZE_BODY = Pt(11)
SIZE_H1 = Pt(14)
SIZE_H2 = Pt(13)
SIZE_H3 = Pt(12)

def set_cell_shading(cell, color_hex):
    shading = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{color_hex}"/>')
    cell._tc.get_or_add_tcPr().append(shading)

def set_cell_border(cell, **kwargs):
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    tcBorders = parse_xml(f'<w:tcBorders {nsdecls("w")}></w:tcBorders>')
    for edge, val in kwargs.items():
        element = parse_xml(
            f'<w:{edge} {nsdecls("w")} w:val="{val["val"]}" w:sz="{val["sz"]}" w:space="0" w:color="{val["color"]}"/>'
        )
        tcBorders.append(element)
    tcPr.append(tcBorders)

def add_formatted_paragraph(doc, text, style='Normal'):
    """Add paragraph with bold and italic formatting."""
    p = doc.add_paragraph()
    p.paragraph_format.space_after = Pt(6)
    p.paragraph_format.space_before = Pt(2)
    
    # Parse inline formatting
    parts = re.split(r'(\*\*.*?\*\*|\[.*?\])', text)
    for part in parts:
        if part.startswith('**') and part.endswith('**'):
            run = p.add_run(part[2:-2])
            run.bold = True
            run.font.name = FONT_BODY
            run.font.size = SIZE_BODY
            run.font.color.rgb = BLACK
        elif part.startswith('[') and part.endswith(']') and 'PGS' in part:
            run = p.add_run(part)
            run.italic = True
            run.font.name = FONT_BODY
            run.font.size = SIZE_BODY
            run.font.color.rgb = ACCENT
        else:
            if part:
                run = p.add_run(part)
                run.font.name = FONT_BODY
                run.font.size = SIZE_BODY
                run.font.color.rgb = BLACK
    return p

def parse_content_file(filepath):
    """Parse a content file into structured sections."""
    with open(filepath, 'r', encoding='utf-8') as f:
        text = f.read()
    
    blocks = []
    lines = text.split('\n')
    current_block = {'type': 'text', 'content': []}
    
    for line in lines:
        stripped = line.strip()
        
        if not stripped or stripped.startswith('===') or stripped.startswith('---'):
            if current_block['content']:
                blocks.append(current_block)
                current_block = {'type': 'text', 'content': []}
            continue
        
        if stripped.startswith('# '):
            if current_block['content']:
                blocks.append(current_block)
            blocks.append({'type': 'h1', 'content': stripped[2:]})
            current_block = {'type': 'text', 'content': []}
        elif stripped.startswith('## '):
            if current_block['content']:
                blocks.append(current_block)
            blocks.append({'type': 'h2', 'content': stripped[3:]})
            current_block = {'type': 'text', 'content': []}
        elif stripped.startswith('### '):
            if current_block['content']:
                blocks.append(current_block)
            blocks.append({'type': 'h3', 'content': stripped[4:]})
            current_block = {'type': 'text', 'content': []}
        elif stripped.startswith('|') and '|' in stripped[1:]:
            if current_block['type'] != 'table':
                if current_block['content']:
                    blocks.append(current_block)
                current_block = {'type': 'table', 'content': []}
            cells = [c.strip() for c in stripped.split('|')[1:-1]]
            current_block['content'].append(cells)
        elif re.match(r'^\d+\.\s', stripped):
            current_block['content'].append(('num', stripped))
        elif stripped.startswith('- ') or stripped.startswith('• '):
            current_block['content'].append(('bullet', stripped[2:]))
        else:
            current_block['content'].append(('text', stripped))
    
    if current_block['content']:
        blocks.append(current_block)
    
    return blocks

def create_table_from_data(doc, rows, is_header=True):
    """Create a styled table from parsed data."""
    if not rows:
        return
    table = doc.add_table(rows=len(rows), cols=len(rows[0]))
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    table.autofit = True
    
    for i, row_data in enumerate(rows):
        for j, cell_text in enumerate(row_data):
            cell = table.cell(i, j)
            cell.text = ''
            p = cell.paragraphs[0]
            run = p.add_run(cell_text)
            run.font.name = FONT_BODY
            run.font.size = Pt(10)
            if is_header and i == 0:
                run.bold = True
                run.font.color.rgb = WHITE
                set_cell_shading(cell, '003366')
            else:
                run.font.color.rgb = BLACK
                if i % 2 == 0:
                    set_cell_shading(cell, 'F8F9FA')
            p.paragraph_format.space_before = Pt(2)
            p.paragraph_format.space_after = Pt(2)
    
    # Add table borders
    tbl = table._tbl
    tblPr = tbl.tblPr if tbl.tblPr is not None else parse_xml(f'<w:tblPr {nsdecls("w")}/>') 
    borders = parse_xml(
        f'<w:tblBorders {nsdecls("w")}>'
        f'<w:top w:val="single" w:sz="4" w:space="0" w:color="E5E7EB"/>'
        f'<w:left w:val="single" w:sz="4" w:space="0" w:color="E5E7EB"/>'
        f'<w:bottom w:val="single" w:sz="4" w:space="0" w:color="E5E7EB"/>'
        f'<w:right w:val="single" w:sz="4" w:space="0" w:color="E5E7EB"/>'
        f'<w:insideH w:val="single" w:sz="4" w:space="0" w:color="E5E7EB"/>'
        f'<w:insideV w:val="single" w:sz="4" w:space="0" w:color="E5E7EB"/>'
        f'</w:tblBorders>'
    )
    tblPr.append(borders)
    
    doc.add_paragraph()  # spacing after table

def build_document_from_content(content_path, output_path, title, subtitle):
    """Build a complete DOCX from a content file."""
    doc = Document()
    
    # Set default font
    style = doc.styles['Normal']
    font = style.font
    font.name = FONT_BODY
    font.size = SIZE_BODY
    font.color.rgb = BLACK
    
    # Set narrow margins
    for section in doc.sections:
        section.top_margin = Cm(2.0)
        section.bottom_margin = Cm(2.0)
        section.left_margin = Cm(2.5)
        section.right_margin = Cm(2.5)
    
    # === COVER PAGE ===
    # Spacer
    for _ in range(3):
        doc.add_paragraph()
    
    # Logo
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run()
    run.add_picture('/root/projects/jg/assets/branding/jvg-logo-medium.png', width=Cm(5))
    
    # Spacer
    for _ in range(3):
        doc.add_paragraph()
    
    # Accent line
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run('━' * 50)
    run.font.color.rgb = ACCENT
    run.font.size = Pt(14)
    
    # Title
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run(title)
    run.bold = True
    run.font.size = Pt(24)
    run.font.color.rgb = PRIMARY
    run.font.name = FONT_BODY
    
    # Subtitle
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run(subtitle)
    run.font.size = Pt(14)
    run.font.color.rgb = RGBColor(0x37, 0x41, 0x51)
    run.font.name = FONT_BODY
    
    # Accent line
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run('━' * 50)
    run.font.color.rgb = ACCENT
    run.font.size = Pt(14)
    
    # Meta info
    for _ in range(3):
        doc.add_paragraph()
    
    for line in ['JvG Consultancy', 'Versie 1.0 — April 2026', 'Vertrouwelijk']:
        p = doc.add_paragraph()
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = p.add_run(line)
        run.font.size = Pt(12)
        run.font.color.rgb = RGBColor(0x37, 0x41, 0x51)
        run.font.name = FONT_BODY
    
    # Page break
    doc.add_page_break()
    
    # === HEADER & FOOTER ===
    section = doc.sections[0]
    header = section.header
    hp = header.paragraphs[0]
    hp.alignment = WD_ALIGN_PARAGRAPH.LEFT
    run = hp.add_run()
    run.add_picture('/root/projects/jg/assets/branding/jvg-logo-small.png', height=Cm(1.2))
    run2 = hp.add_run('  ' + title)
    run2.font.size = Pt(8)
    run2.font.color.rgb = RGBColor(0x37, 0x41, 0x51)
    run2.font.name = FONT_BODY
    
    footer = section.footer
    fp = footer.paragraphs[0]
    fp.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = fp.add_run('JvG Consultancy — PGS-15 Audit Toolkit  |  April 2026  |  Pagina ')
    run.font.size = Pt(8)
    run.font.color.rgb = RGBColor(0x37, 0x41, 0x51)
    run.font.name = FONT_BODY
    # Page number field
    fldChar1 = parse_xml(f'<w:fldChar {nsdecls("w")} w:fldCharType="begin"/>')
    run._r.append(fldChar1)
    instrText = parse_xml(f'<w:instrText {nsdecls("w")} xml:space="preserve"> PAGE </w:instrText>')
    run._r.append(instrText)
    fldChar2 = parse_xml(f'<w:fldChar {nsdecls("w")} w:fldCharType="end"/>')
    run._r.append(fldChar2)
    
    # === PARSE CONTENT ===
    blocks = parse_content_file(content_path)
    
    for block in blocks:
        if block['type'] == 'h1':
            doc.add_page_break()
            p = doc.add_paragraph()
            run = p.add_run(block['content'])
            run.bold = True
            run.font.size = SIZE_H1
            run.font.color.rgb = PRIMARY
            run.font.name = FONT_BODY
            p.paragraph_format.space_before = Pt(12)
            p.paragraph_format.space_after = Pt(8)
        elif block['type'] == 'h2':
            p = doc.add_paragraph()
            run = p.add_run(block['content'])
            run.bold = True
            run.font.size = SIZE_H2
            run.font.color.rgb = PRIMARY
            run.font.name = FONT_BODY
            p.paragraph_format.space_before = Pt(12)
            p.paragraph_format.space_after = Pt(6)
        elif block['type'] == 'h3':
            p = doc.add_paragraph()
            run = p.add_run(block['content'])
            run.bold = True
            run.font.size = SIZE_H3
            run.font.color.rgb = RGBColor(0x37, 0x41, 0x51)
            run.font.name = FONT_BODY
            p.paragraph_format.space_before = Pt(8)
            p.paragraph_format.space_after = Pt(4)
        elif block['type'] == 'table':
            create_table_from_data(doc, block['content'])
        elif block['type'] == 'text':
            for item_type, item_text in block['content']:
                if item_type == 'bullet':
                    p = doc.add_paragraph(style='List Bullet')
                    p.clear()
                    # Re-add with formatting
                    parts = re.split(r'(\*\*.*?\*\*|\[.*?\])', item_text)
                    for part in parts:
                        if part.startswith('**') and part.endswith('**'):
                            run = p.add_run(part[2:-2])
                            run.bold = True
                        elif part.startswith('[') and part.endswith(']') and 'PGS' in part:
                            run = p.add_run(part)
                            run.italic = True
                            run.font.color.rgb = ACCENT
                        else:
                            if part:
                                run = p.add_run(part)
                        run.font.name = FONT_BODY
                        run.font.size = SIZE_BODY
                    p.paragraph_format.space_after = Pt(3)
                elif item_type == 'num':
                    p = doc.add_paragraph(style='List Bullet')
                    p.clear()
                    parts = re.split(r'(\*\*.*?\*\*|\[.*?\])', item_text)
                    for part in parts:
                        if part.startswith('**') and part.endswith('**'):
                            run = p.add_run(part[2:-2])
                            run.bold = True
                        elif part.startswith('[') and part.endswith(']') and 'PGS' in part:
                            run = p.add_run(part)
                            run.italic = True
                            run.font.color.rgb = ACCENT
                        else:
                            if part:
                                run = p.add_run(part)
                        run.font.name = FONT_BODY
                        run.font.size = SIZE_BODY
                    p.paragraph_format.space_after = Pt(3)
                elif item_type == 'text':
                    add_formatted_paragraph(doc, item_text)
    
    doc.save(output_path)
    print(f'  ✓ {output_path} ({os.path.getsize(output_path):,} bytes)')

def build_audit_report_template(output_path):
    """Build the empty audit report template."""
    doc = Document()
    
    style = doc.styles['Normal']
    font = style.font
    font.name = FONT_BODY
    font.size = SIZE_BODY
    font.color.rgb = BLACK
    
    for section in doc.sections:
        section.top_margin = Cm(2.0)
        section.bottom_margin = Cm(2.0)
        section.left_margin = Cm(2.5)
        section.right_margin = Cm(2.5)
    
    # === COVER PAGE ===
    for _ in range(3):
        doc.add_paragraph()
    
    # Logo
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run()
    run.add_picture('/root/projects/jg/assets/branding/jvg-logo-medium.png', width=Cm(5))
    
    for _ in range(2):
        doc.add_paragraph()
    
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run('━' * 50)
    run.font.color.rgb = ACCENT
    run.font.size = Pt(14)
    
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run('PGS-15 Audit Rapport')
    run.bold = True
    run.font.size = Pt(26)
    run.font.color.rgb = PRIMARY
    run.font.name = FONT_BODY
    
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run('[Bedrijfsnaam]')
    run.font.size = Pt(16)
    run.font.color.rgb = RGBColor(0x37, 0x41, 0x51)
    run.font.name = FONT_BODY
    
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run('━' * 50)
    run.font.color.rgb = ACCENT
    run.font.size = Pt(14)
    
    for _ in range(4):
        doc.add_paragraph()
    
    fields = [
        ('Datum audit:', '[DD-MM-JJJJ]'),
        ('Auditor:', '[Naam auditor]'),
        ('Referentie:', '[Auditreferentie]'),
        ('Versie:', '1.0'),
    ]
    for label, value in fields:
        p = doc.add_paragraph()
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = p.add_run(label + '  ')
        run.bold = True
        run.font.size = Pt(11)
        run.font.color.rgb = PRIMARY
        run.font.name = FONT_BODY
        run = p.add_run(value)
        run.font.size = Pt(11)
        run.font.color.rgb = RGBColor(0x37, 0x41, 0x51)
        run.font.name = FONT_BODY
    
    for _ in range(3):
        doc.add_paragraph()
    
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run('JvG Consultancy — PGS-15 Audit Toolkit')
    run.font.size = Pt(10)
    run.font.color.rgb = RGBColor(0x37, 0x41, 0x51)
    run.font.name = FONT_BODY
    
    doc.add_page_break()
    
    # === HEADER & FOOTER ===
    section = doc.sections[0]
    header = section.header
    hp = header.paragraphs[0]
    hp.alignment = WD_ALIGN_PARAGRAPH.LEFT
    run = hp.add_run()
    run.add_picture('/root/projects/jg/assets/branding/jvg-logo-small.png', height=Cm(1.2))
    run2 = hp.add_run('  PGS-15 Audit Rapport — [Bedrijfsnaam]')
    run2.font.size = Pt(8)
    run2.font.color.rgb = RGBColor(0x37, 0x41, 0x51)
    run2.font.name = FONT_BODY
    
    footer = section.footer
    fp = footer.paragraphs[0]
    fp.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = fp.add_run('JvG Consultancy — PGS-15 Audit Toolkit  |  April 2026  |  Pagina ')
    run.font.size = Pt(8)
    run.font.color.rgb = RGBColor(0x37, 0x41, 0x51)
    run.font.name = FONT_BODY
    fldChar1 = parse_xml(f'<w:fldChar {nsdecls("w")} w:fldCharType="begin"/>')
    run._r.append(fldChar1)
    instrText = parse_xml(f'<w:instrText {nsdecls("w")} xml:space="preserve"> PAGE </w:instrText>')
    run._r.append(instrText)
    fldChar2 = parse_xml(f'<w:fldChar {nsdecls("w")} w:fldCharType="end"/>')
    run._r.append(fldChar2)
    
    # === SECTIONS ===
    def add_section_heading(doc, text):
        p = doc.add_paragraph()
        run = p.add_run(text)
        run.bold = True
        run.font.size = SIZE_H1
        run.font.color.rgb = PRIMARY
        run.font.name = FONT_BODY
        p.paragraph_format.space_before = Pt(16)
        p.paragraph_format.space_after = Pt(8)
    
    def add_field(doc, label, placeholder=''):
        p = doc.add_paragraph()
        run = p.add_run(label + ' ')
        run.bold = True
        run.font.size = SIZE_BODY
        run.font.color.rgb = BLACK
        run.font.name = FONT_BODY
        run = p.add_run(placeholder)
        run.font.size = SIZE_BODY
        run.font.color.rgb = RGBColor(0x9C, 0xA3, 0xAF)
        run.font.name = FONT_BODY
        p.paragraph_format.space_after = Pt(4)
    
    # 1. Opdrachtgever
    add_section_heading(doc, '1. Opdrachtgever')
    add_field(doc, 'Bedrijfsnaam:', '[Bedrijfsnaam]')
    add_field(doc, 'Locatie:', '[Adres, postcode, plaats]')
    add_field(doc, 'Contactpersoon:', '[Naam, functie, telefoon, e-mail]')
    add_field(doc, 'KVK-nummer:', '[KVK-nummer]')
    
    # 2. Audit scope
    add_section_heading(doc, '2. Audit scope')
    add_field(doc, 'Opslagvoorzieningen:', '[Omschrijving van de geauditeerde voorzieningen]')
    add_field(doc, 'Periode:', '[Auditdatum of periode]')
    add_field(doc, 'Doel:', '[Doelstelling van de audit]')
    
    # 3. Werkingssfeer
    add_section_heading(doc, '3. Werkingssfeer')
    p = doc.add_paragraph('Is PGS-15 van toepassing op deze inrichting?')
    p.paragraph_format.space_after = Pt(6)
    add_field(doc, 'PGS-15 van toepassing:', '[Ja / Nee / Gedeeltelijk]')
    add_field(doc, 'ADR-klassen:', '[Klassen die aanwezig zijn]')
    add_field(doc, 'Totale hoeveelheid:', '[kg/liter per klasse en totaal]')
    add_field(doc, 'Beschermingsniveau:', '[1 / 2a / 3 / 4 / N.v.t.]')
    add_field(doc, 'Vergunningplichtig:', '[Ja / Nee — Activiteitenbesluit / Omgevingsvergunning]')
    
    # 4. Bevindingen
    add_section_heading(doc, '4. Bevindingen')
    p = doc.add_paragraph('Per sectie worden de bevindingen vastgelegd in onderstaande tabel.')
    p.paragraph_format.space_after = Pt(8)
    
    # Empty findings table
    findings_headers = ['Nr', 'Onderwerp', 'Bronvermelding [PGS 15:2016]', 'Bevinding', 'Classificatie', 'Opmerking']
    findings_rows = [['', '', '', '', 'conform / afwijking / kritiek', ''] for _ in range(8)]
    create_table_from_data(doc, [findings_headers] + findings_rows)
    
    # 5. Samenvatting
    add_section_heading(doc, '5. Samenvatting')
    p = doc.add_paragraph()
    run = p.add_run('Totaal controlepunten:')
    run.bold = True
    run.font.name = FONT_BODY
    run.font.size = SIZE_BODY
    add_field(doc, 'Conform:', '[Aantal]')
    add_field(doc, 'Afwijking:', '[Aantal]')
    add_field(doc, 'Kritieke afwijking:', '[Aantal]')
    add_field(doc, 'Niet van toepassing:', '[Aantal]')
    add_field(doc, 'Percentage conformiteit:', '[%] (conform / (totaal – n.v.t.))')
    
    # 6. Aanbevelingen
    add_section_heading(doc, '6. Aanbevelingen')
    rec_headers = ['Nr', 'Aanbeveling', 'Verwijzing PGS 15', 'Prioriteit', 'Termijn', 'Verantwoordelijke']
    rec_rows = [['', '', '', 'Hoog / Medium / Laag', '', ''] for _ in range(6)]
    create_table_from_data(doc, [rec_headers] + rec_rows)
    
    # 7. Bijlagen
    add_section_heading(doc, '7. Bijlagen')
    bijlagen = [
        'Bijlage A — PGS-15 Audit Checklist (ingevuld)',
        'Bijlage B — Fotodocumentatie',
        'Bijlage C — Overzicht documenten',
        'Bijlage D — Stoffenlijst / Journaal (kopie)',
    ]
    for item in bijlagen:
        p = doc.add_paragraph(item, style='List Bullet')
        p.paragraph_format.space_after = Pt(4)
    
    # Signature block
    doc.add_paragraph()
    doc.add_paragraph()
    p = doc.add_paragraph('─' * 40)
    p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    run = p.add_run('Naam auditor')
    run.font.size = SIZE_BODY
    run.font.name = FONT_BODY
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    run = p.add_run('Handtekening: ________________________')
    run.font.size = SIZE_BODY
    run.font.name = FONT_BODY
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    run = p.add_run('Datum: ________________________')
    run.font.size = SIZE_BODY
    run.font.name = FONT_BODY
    
    doc.save(output_path)
    print(f'  ✓ {output_path} ({os.path.getsize(output_path):,} bytes)')

def main():
    base = '/root/projects/jg/2026-pgs15-audit-toolkit'
    out_dir = os.path.join(base, 'deliverables', 'docx')
    os.makedirs(out_dir, exist_ok=True)
    
    print('PGS-15 Audit Toolkit — DOCX Generator v1.0')
    print('=' * 50)
    
    print('\n📄 Document 1: Basishandleiding')
    build_document_from_content(
        os.path.join(base, 'working', '01_pgs15_basishandleiding_content.txt'),
        os.path.join(out_dir, 'PGS15_Basishandleiding_v1.0.docx'),
        'PGS-15 Basishandleiding',
        'Opslag van Verpakte Gevaarlijke Stoffen'
    )
    
    print('\n📄 Document 2: Audit Procedure')
    build_document_from_content(
        os.path.join(base, 'working', '02_pgs15_audit_procedure_content.txt'),
        os.path.join(out_dir, 'PGS15_Audit_Procedure_v1.0.docx'),
        'PGS-15 Audit Procedure',
        'Stap-voor-Stap Handleiding'
    )
    
    print('\n📄 Document 3: Audit Rapport Template')
    build_audit_report_template(
        os.path.join(out_dir, 'PGS15_Audit_Rapport_Template_v1.0.docx')
    )
    
    print('\n📄 Document 4: Audit Checklist')
    build_document_from_content(
        os.path.join(base, 'working', '03_pgs15_checklist_docx_content.txt'),
        os.path.join(out_dir, 'PGS15_Audit_Checklist_v1.0.docx'),
        'PGS-15 Audit Checklist',
        'Controlepunten voor Opslag van Gevaarlijke Stoffen'
    )
    
    print('\n' + '=' * 50)
    print('✅ Alle 4 documenten gegenereerd.')
    
    # Verify
    print('\nVerificatie:')
    for fname in ['PGS15_Basishandleiding_v1.0.docx', 'PGS15_Audit_Procedure_v1.0.docx', 'PGS15_Audit_Rapport_Template_v1.0.docx', 'PGS15_Audit_Checklist_v1.0.docx']:
        fpath = os.path.join(out_dir, fname)
        size = os.path.getsize(fpath)
        status = '✅' if size > 10240 else '⚠️ < 10KB'
        print(f'  {status} {fname} — {size:,} bytes')

if __name__ == '__main__':
    main()
