#!/usr/bin/env python3
"""Minimal fix: Replace organogram ASCII with image only."""

from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
from playwright.sync_api import sync_playwright
import shutil
import os

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

# Archive original
shutil.copy2(SRC, ARCHIVE)

# Generate simple organogram image
HTML = """<html><head><meta charset="utf-8"><style>
body{font-family:Calibri;padding:20px;width:780px;margin:0;background:#fff}
h1{text-align:center;font-size:16pt;color:#003366;margin-bottom:20px}
.org-box{text-align:center;padding:12px;border-radius:8px;border:2px solid;margin:8px auto;min-width:180px;display:inline-block}
.level1{background:#003366;color:#fff}
.level2{background:#374151;color:#fff}
.level3{background:#E5E7EB;color:#1F2937}
.level4{background:#F8F9FA;color:#1F2937;border:2px solid #E5E7EB}
.legend{display:flex;justify-content:center;gap:15px;margin-top:25px;font-size:9pt}
.legend div{display:flex;align-items:center;gap:5px}
.color-box{width:12px;height:12px;border-radius:2px}
</style></head><body>
<h1>Organisatorische Structuur — Phoenix Metals B.V.</h1>
<div style="text-align:center">
<div class="org-box level1" style="margin-bottom:5px">
  <b>Managing Director</b><br>Stijn van Zelst
</div>
<div style="width:2px;height:20px;background:#9CA3AF;margin:0 auto"></div>
<div style="display:flex;justify-content:center;gap:30px">
  <div class="org-box level2" style="margin-top:5px">
    <b>Operations Manager</b>
  </div>
  <div class="org-box level2" style="margin-top:5px">
    <b>HSE Manager</b>
  </div>
  <div class="org-box level2" style="margin-top:5px">
    <b>Maintenance Manager</b>
  </div>
</div>
<div style="display:flex;justify-content:center;gap:25px;margin-top:15px">
  <div class="org-box level4">
    <b>Field Operators</b>
  </div>
  <div class="org-box level3">
    <b>HSE Supervisor</b>
  </div>
  <div class="org-box level4">
    <b>E&I Technicians</b>
  </div>
</div>
<div style="width:2px;height:25px;background:#9CA3AF;margin:15px auto"></div>
<div class="org-box level3" style="max-width:300px">
  <b>Office Staff / Administration</b><br>Administratie & Ondersteuning
</div>
</div>
<div class="legend">
  <div><div class="color-box" style="background:#003366"></div>Directie</div>
  <div><div class="color-box" style="background:#374151"></div>Management</div>
  <div><div class="color-box" style="background:#E5E7EB"></div>Supervisie</div>
  <div><div class="color-box" style="background:#F8F9FA;border:1px solid #D1D5DB"></div>Uitvoering</div>
</div>
</body></html>"""

with open("/tmp/org.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/org.html")
    pg.screenshot(path="/tmp/org.png")
    br.close()

# Read original document
doc = Document(SRC)

# Find "5.1 Veiligheidsorganigram" and replace next paragraph with image
found = False
for i, p in enumerate(doc.paragraphs):
    if "5.1 Veiligheidsorganigram" in p.text and "Heading" in p.style.name:
        # Delete the next few paragraphs (ASCII art)
        j = i + 1
        while j < len(doc.paragraphs):
            if "5.2" in doc.paragraphs[j].text or doc.paragraphs[j].text.strip() == "":
                break
            doc.paragraphs[j]._element.getparent().remove(doc.paragraphs[j]._element)
        
        # Insert image paragraph
        img_para = doc.add_paragraph()
        img_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = img_para.add_run()
        run.add_picture("/tmp/org.png", width=Inches(5.5))
        
        # Move it to the right position
        img_el = img_para._element
        img_el.getparent().remove(img_el)
        p._element.addnext(img_el)
        
        found = True
        break

# Also find Bijlage A and do the same
for i, p in enumerate(doc.paragraphs):
    if "Bijlage A: Organigram" in p.text and "Heading" in p.style.name:
        # Delete ASCII art under it
        j = i + 1
        while j < len(doc.paragraphs):
            p2 = doc.paragraphs[j]
            if p2.text.strip().startswith("┌") or p2.text.strip().startswith("│"):
                p2._element.getparent().remove(p2._element)
            else:
                break
            j += 1
        
        # Insert image
        img_para = doc.add_paragraph()
        img_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = img_para.add_run()
        run.add_picture("/tmp/org.png", width=Inches(5.5))
        img_el = img_para._element
        img_el.getparent().remove(img_el)
        p._element.addnext(img_el)
        
        found = True
        break

doc.save(DST)
os.unlink("/tmp/org.png")
os.unlink("/tmp/org.html")

print(f"✅ Fixed organogram → {DST}")
print(f"✅ Archived → {ARCHIVE}")