#!/usr/bin/env python3
"""Fix PBZO v1.0 → v1.1: Professional organogram + polished tables."""

import shutil, os, tempfile
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

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"

# Step 0: Archive
ARCHIVE.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(SRC, ARCHIVE)

# Step 1: Generate organogram image
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:28px;letter-spacing:.5px}
table.org-t{border-collapse:collapse;margin:0 auto}
table.org-t td{padding:0;text-align:center;vertical-align:top}
.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}
.vline{width:2px;height:26px;background:#9CA3AF;margin:0 auto}
.hline{border-top:2px solid #9CA3AF}
.legend{margin-top:22px;display:flex;justify-content:center;gap:20px;font-size:9pt;color:#6B7280}
.legend>div{display:flex;align-items:center;gap:6px}
.legend .sw{width:14px;height:14px;border-radius:3px}
</style></head><body>
<div class="org-title">Organisatorische Structuur — Phoenix Metals B.V.</div>
<table class="org-t">
<tr><td colspan="7"><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></td></tr>
<tr><td colspan="7"><div class="vline"></div></td></tr>
<tr><td colspan="7"><table style="margin:0 auto;border-collapse:collapse"><tr>
<td style="width:130px" class="hline"></td>
<td style="width:2px;height:2px;background:#9CA3AF"></td>
<td style="width:130px" class="hline"></td>
<td style="width:2px;height:2px;background:#9CA3AF"></td>
<td style="width:130px" class="hline"></td>
</tr></table></td></tr>
<tr><td style="width:130px"></td><td><div class="vline"></div></td>
<td style="width:40px"></td><td><div class="vline"></div></td>
<td style="width:40px"></td><td><div class="vline"></div></td><td style="width:130px"></td></tr>
<tr><td></td><td><div class="box l2" style="margin:0 auto"><div class="r">Operations<br>Manager</div></div></td>
<td></td><td><div class="box l2" style="margin:0 auto"><div class="r">HSE<br>Manager</div></div></td>
<td></td><td><div class="box l2" style="margin:0 auto"><div class="r">Maintenance<br>Manager</div></div></td><td></td></tr>
<tr><td></td><td><div class="vline"></div></td><td></td><td><div class="vline"></div></td><td></td><td><div class="vline"></div></td><td></td></tr>
<tr><td></td><td><div class="box l4" style="margin:0 auto"><div class="r">Field<br>Operators</div></div></td>
<td></td><td><div class="box l3" style="margin:0 auto"><div class="r">HSE<br>Supervisor</div></div></td>
<td></td><td><div class="box l4" style="margin:0 auto"><div class="r">E&I<br>Technicians</div></div></td><td></td></tr>
<tr><td colspan="7" style="height:18px"></td></tr>
<tr><td colspan="7"><div class="vline"></div></td></tr>
<tr><td colspan="7"><div class="box l3" style="margin:0 auto;min-width:210px"><div class="r">Office Staff / Administration</div><div class="n">Administratie & Ondersteuning</div></div></td></tr>
</table>
<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>"""

img_path = "/tmp/_pbzo_organogram.png"
with tempfile.NamedTemporaryFile(suffix='.html', mode='w', delete=False) as f:
    f.write(HTML)
    html_path = f.name

with sync_playwright() as p:
    br = p.chromium.launch()
    pg = br.new_page(viewport={"width": 820, "height": 600})
    pg.goto(f"file://{html_path}")
    pg.wait_for_timeout(500)
    pg.query_selector("body").screenshot(path=img_path)
    br.close()
os.unlink(html_path)
print(f"✓ Organogram image generated")

# Step 2: Work with DOCX - use HARD-CODED indices from Heading analysis
# Heading paragraphs (confirmed from original document):
#   116: [Heading 1] 5. Organisatorische structuur
#   117: [Heading 2] 5.1 Veiligheidsorganigram
#   129: [Heading 2] 5.2 Rollen en verantwoordelijkheden
#   166: [Heading 2] Bijlage A: Organigram
#   193: [Heading 2] Bijlage B: Overzicht VBS-elementen en documenten

doc = Document(str(SRC))
body = doc.element.body

# 2a: Remove ASCII art between §5.1 intro (118) and §5.2 heading (129)
# Keep paragraph 118 (intro text), remove 119-128, keep 129 (§5.2 heading)
s52_el = doc.paragraphs[129]._element  # Heading 5.2
intro_el = doc.paragraphs[118]._element  # "De veiligheidsorganisatiestructuur..."

to_remove = []
el = intro_el.getnext()
while el is not None and el != s52_el:
    to_remove.append(el)
    el = el.getnext()

for el in to_remove:
    body.remove(el)
print(f"✓ Removed {len(to_remove)} elements from §5.1 (ASCII art)")

# Insert image after intro
img_para = doc.add_paragraph()
img_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = img_para.add_run()
run.add_picture(img_path, width=Inches(5.5))
img_el = img_para._element
body.remove(img_el)
intro_el.addnext(img_el)
print("✓ Inserted organogram image in §5.1")

# 2b: Remove ASCII art in Bijlage A (between heading 166 and heading 193)
bijA_el = doc.paragraphs[166]._element  # Heading "Bijlage A"
bijB_el = doc.paragraphs[193]._element  # Heading "Bijlage B"

to_remove2 = []
el = bijA_el.getnext()
while el is not None and el != bijB_el:
    to_remove2.append(el)
    el = el.getnext()

for el in to_remove2:
    body.remove(el)
print(f"✓ Removed {len(to_remove2)} elements from Bijlage A (ASCII art)")

# Insert image after Bijlage A heading
img_para2 = doc.add_paragraph()
img_para2.alignment = WD_ALIGN_PARAGRAPH.CENTER
run2 = img_para2.add_run()
run2.add_picture(img_path, width=Inches(5.5))
img_el2 = img_para2._element
body.remove(img_el2)
bijA_el.addnext(img_el2)
print("✓ Inserted organogram image in Bijlage A")

# Step 3: Polish tables
for table in doc.tables:
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    for j, row in enumerate(table.rows):
        for cell in row.cells:
            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)
            
            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"
            
            tc_pr = cell._element.get_or_add_tcPr()
            for old in tc_pr.findall(qn('w:shd')):
                tc_pr.remove(old)
            tc_pr.append(parse_xml(f'<w:shd {nsdecls("w")} w:fill="{bg}" w:val="clear"/>'))
            
            for old in tc_pr.findall(qn('w:tcMar')):
                tc_pr.remove(old)
            tc_mar = OxmlElement('w:tcMar')
            for side in ['top', 'left', 'bottom', 'right']:
                n = OxmlElement(f'w:{side}')
                n.set(qn('w:w'), '60')
                n.set(qn('w:type'), 'dxa')
                tc_mar.append(n)
            tc_pr.append(tc_mar)

# Step 4: Save
doc.save(str(DST))
os.unlink(img_path)
print(f"\n✅ Saved → {DST}")
print(f"✅ Archive → {ARCHIVE}")
