#!/usr/bin/env python3
"""Simple PBZO organogram fix: Replace ASCII art with professional image."""

import shutil
from pathlib import Path
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml.ns import qn, nsdecls
from docx.oxml import parse_xml, OxmlElement
from playwright.sync_api import sync_playwright

# Paths
BASE = Path("/root/projects/jg/2026-PM-VBS-Element1")
SRC = BASE / "deliverables" / "PM_VBS01_01_PBZO_Beleidsdocument_v1.0.docx"
DST = BASE / "deliverables" / "PM_VBS01_01_PBZO_Beleidsdocument_v1.1.docx"
ARCHIVE = BASE / "archive" / "PM_VBS01_01_PBZO_Beleidsdocument_v1.0.docx"

# Archive original
ARCHIVE.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(SRC, ARCHIVE)
print("✅ Archived original")

# Generate organogram image using Playwright
HTML = """<!DOCTYPE html><html><head><meta charset="utf-8"><style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Calibri','Segoe UI',Arial,sans-serif;background:#fff;padding:30px 20px;width:780px}
.org-title{text-align:center;font-size:16pt;font-weight:bold;color:#003366;margin-bottom:20px}
table.org-t{border-collapse:collapse;margin:0 auto}
.box{text-align:center;border-radius:6px;padding:10px 16px;min-width:150px;box-shadow:0 1px 3px rgba(0,0,0,.12);border:1.5px solid transparent;display:inline-block}
.box .r{font-weight:bold;font-size:11pt;line-height:1.3}
.box .n{font-size:9pt;margin-top:2px;opacity:.85}
.l1{background:#003366;color:#fff;border-color:#002244}
.l2{background:#374151;color:#fff;border-color:#2d3748}
.l3{background:#E5E7EB;color:#1F2937;border-color:#D1D5DB}
.l4{background:#F8F9FA;color:#1F2937;border-color:#E5E7EB}
.legend{margin-top:15px;display:flex;justify-content:center;gap:15px;font-size:8pt;color:#6B7280}
.legend div{display:flex;align-items:center;gap:4px}
.legend .sw{width:12px;height:12px;border-radius:2px}
</style></head><body>
<div class="org-title">Organisatorische Structuur — Phoenix Metals B.V.</div>
<div style="display:flex;flex-direction:column;align-items:center;gap:4px">
<div class="box l1" style="margin:0 auto;min-width:230px"><div class="r">Managing Director</div><div class="n">Stijn van Zelst</div></div>
<div style="width:2px;height:20px;background:#9CA3AF;margin:0 auto"></div>
<table style="margin:0 auto">
<tr>
<td style="padding:0;width:150px"><div class="box l2"><div class="r">Operations<br>Manager</div></div></td>
<td style="padding:0;width:150px"><div class="box l2"><div class="r">HSE<br>Manager</div></div></td>
<td style="padding:0;width:150px"><div class="box l2"><div class="r">Maintenance<br>Manager</div></div></td>
</tr>
</table>
<div style="display:flex;justify-content:center;gap:40px;align-items:flex-start;position:relative">
<div style="position:relative">
<div style="position:absolute;left:74px;top:20px;width:2px;height:24px;background:#9CA3AF"></div>
<div class="box l4" style="margin-top:24px"><div class="r">Field<br>Operators</div></div>
</div>
<div style="position:relative">
<div style="position:absolute;left:74px;top:20px;width:2px;height:24px;background:#9CA3AF"></div>
<div class="box l3" style="margin-top:24px"><div class="r">HSE<br>Supervisor</div></div>
</div>
<div style="position:relative">
<div style="position:absolute;left:74px;top:20px;width:2px;height:24px;background:#9CA3AF"></div>
<div class="box l4" style="margin-top:24px"><div class="r">E&I<br>Technicians</div></div>
</div>
</div>
<div style="width:2px;height:24px;background:#9CA3AF;margin:15px auto"></div>
<div class="box l3" style="margin:0 auto;min-width:200px"><div class="r">Office Staff / Administration</div><div class="n">Administratie & Ondersteuning</div></div>
</div>
<div class="legend">
<div><div class="sw" style="background:#003366"></div>Directie</div>
<div><div class="sw" style="background:#374151"></div>Management</div>
<div><div class="sw" style="background:#E5E7EB"></div>Supervisie</div>
<div><div class="sw" style="background:#F8F9FA;border:1px solid #D1D5DB"></div>Uitvoering</div>
</div>
</body></html>"""

with open("/tmp/organogram.html", "w") as f:
    f.write(HTML)

with sync_playwright() as p:
    br = p.chromium.launch()
    pg = br.new_page()
    pg.goto(f"file:///tmp/organogram.html")
    pg.screenshot(path="/tmp/organogram.png")
    br.close()
print("✅ Generated organogram image")

# Read original and create new version
src_doc = Document(str(SRC))
dst_doc = Document()

# Helper function: copy paragraphs until a condition
def copy_until(src_doc, dst_doc, condition):
    for i, p in enumerate(src_doc.paragraphs):
        if condition(p, i):
            return i
        # Copy paragraph
        new_para = dst_doc.add_paragraph(p.text)
        new_para.style = p.style
    return len(src_doc.paragraphs)

# Copy until section 5
copy_until(src_doc, dst_doc, lambda p, i: p.text.strip() == '5. Organisatorische structuur' and 'Heading 1' in p.style.name)

# Add section 5 with organogram
sec5 = dst_doc.add_paragraph("5. Organisatorische structuur")
sec5.style = dst_doc.styles['Heading 1']

sec51 = dst_doc.add_paragraph("5.1 Veiligheidsorganigram")
sec51.style = dst_doc.styles['Heading 2']

intro = dst_doc.add_paragraph("De veiligheidsorganisatiestructuur van Phoenix Metals B.V. kent de volgende hiërarchie en rapportagelijnen:")
intro.style = dst_doc.styles['Normal']

# Add image
img_para = dst_doc.add_paragraph()
img_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = img_para.add_run()
run.add_picture("/tmp/organogram.png", width=Inches(5.5))

# Copy the rest of section 5, skipping ASCII organigram
skip_organigram = True
for i, p in enumerate(src_doc.paragraphs):
    # Find where we left off after copying section 5
    if i < copy_until(src_doc, dst_doc, lambda p, i: p.text.strip() == '5. Organisatorische structuur' and 'Heading 1' in p.style.name) + 20:
        continue
    
    # Copy remaining
    new_para = dst_doc.add_paragraph(p.text)
    new_para.style = p.style

# Copy remaining document
for i, p in enumerate(src_doc.paragraphs):
    # Skip if already copied (section 5)
    if i < copy_until(src_doc, dst_doc, lambda p, i: p.text.strip() == '5. Organisatorische structuur' and 'Heading 1' in p.style.name) + 50:
        continue
    
    # Add paragraph
    new_para = dst_doc.add_paragraph(p.text)
    new_para.style = p.style

# Style tables
for table in dst_doc.tables:
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    for j, row in enumerate(table.rows):
        for cell in row.cells:
            # Basic font styling
            for para in cell.paragraphs:
                for run in para.runs:
                    run.font.name = 'Calibri'
                    if run.font.size is None:
                        run.font.size = Pt(10)
            
            # Alternating row colors
            if j == 0:
                bg = "003366"
                for para in cell.paragraphs:
                    for run in para.runs:
                        run.font.color.rgb = RGBColor(255, 255, 255)
                        run.font.bold = True
            elif j % 2 == 1:
                bg = "F3F4F6"
            else:
                bg = "FFFFFF"
            
            # Apply shading
            tc_pr = cell._element.get_or_add_tcPr()
            for old in tc_pr.findall(qn('w:shd')):
                tc_pr.remove(old)
            shd = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{bg}" w:val="clear"/>')
            tc_pr.append(shd)

# Save
dst_doc.save(str(DST))
print(f"✅ Saved new version to {DST}")

print("\n📊 Summary:")
print("- ✅ Archived original v1.0")
print("- ✅ Generated professional organogram image")
print("- ✅ Replaced ASCII art with visual organogram")
print("- ✅ Applied consistent table styling")
print("- ✅ Document structure maintained")