#!/usr/bin/env python3
"""Markdown -> sauberes, formatiertes .docx (python-docx). Für den aws-Businessplan.
Unterstützt: # ## ### Überschriften, **fett**, Aufzählungen, Tabellen (| |), Bilder (![](IMG_KEY)), > Intro.
"""
import sys, re
from docx import Document
from docx.shared import Pt, Cm, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT

IMAGES = {
    "IMG_HERO": ("../marketing/ad-assets/plappi_06.png", 7.0),
    "IMG_LIFESTYLE": ("../marketing/ad-assets/plappi_16.jpg", 14.0),
}
BRAND = RGBColor(0x1a, 0x23, 0x5e)  # dunkles Plappi-Blau für Überschriften

def add_runs(par, text):
    """**fett** inline parsen."""
    for i, part in enumerate(re.split(r'(\*\*.+?\*\*)', text)):
        if not part:
            continue
        if part.startswith('**') and part.endswith('**'):
            r = par.add_run(part[2:-2]); r.bold = True
        else:
            par.add_run(part)

def build(md_path, out_path):
    doc = Document()
    # Basis-Stil
    st = doc.styles['Normal']; st.font.name = 'Calibri'; st.font.size = Pt(10.5)
    for h, sz in (('Heading 1', 16), ('Heading 2', 13), ('Heading 3', 11.5)):
        s = doc.styles[h]; s.font.color.rgb = BRAND; s.font.size = Pt(sz)

    lines = open(md_path, encoding='utf-8').read().splitlines()
    i = 0
    while i < len(lines):
        ln = lines[i].rstrip()
        # Bild
        m = re.match(r'!\[.*?\]\((IMG_\w+)\)', ln)
        if m and m.group(1) in IMAGES:
            path, width = IMAGES[m.group(1)]
            p = doc.add_paragraph(); p.alignment = WD_ALIGN_PARAGRAPH.CENTER
            p.add_run().add_picture(path, width=Cm(width))
            i += 1; continue
        # Tabelle
        if ln.startswith('|') and i+1 < len(lines) and re.match(r'^\|[\s:|-]+\|?\s*$', lines[i+1]):
            rows = []
            while i < len(lines) and lines[i].lstrip().startswith('|'):
                if re.match(r'^\s*\|[\s:|-]+\|?\s*$', lines[i]):
                    i += 1; continue
                cells = [c.strip() for c in lines[i].strip().strip('|').split('|')]
                rows.append(cells); i += 1
            if rows:
                ncol = max(len(r) for r in rows)
                tbl = doc.add_table(rows=0, cols=ncol); tbl.style = 'Light Grid Accent 1'
                tbl.alignment = WD_TABLE_ALIGNMENT.CENTER
                for ri, r in enumerate(rows):
                    cells = tbl.add_row().cells
                    for ci in range(ncol):
                        txt = r[ci] if ci < len(r) else ''
                        cell_par = cells[ci].paragraphs[0]
                        add_runs(cell_par, txt)
                        for run in cell_par.runs:
                            run.font.size = Pt(9)
                            if ri == 0: run.bold = True
                doc.add_paragraph()
            continue
        # Überschriften
        if ln.startswith('### '):
            doc.add_heading(ln[4:], level=3); i += 1; continue
        if ln.startswith('## '):
            doc.add_heading(ln[3:], level=2); i += 1; continue
        if ln.startswith('# '):
            h = doc.add_heading(ln[2:], level=0)
            for r in h.runs: r.font.color.rgb = BRAND
            i += 1; continue
        # Trennlinie
        if ln.strip() == '---':
            i += 1; continue
        # Intro-Zitat
        if ln.startswith('> '):
            p = doc.add_paragraph(); p.paragraph_format.left_indent = Cm(0.3)
            r = p.add_run(re.sub(r'^\*\*|\*\*', '', ln[2:])); r.italic = True; r.font.size = Pt(9.5); r.font.color.rgb = RGBColor(0x55,0x55,0x55)
            i += 1; continue
        # Aufzählung
        if re.match(r'^[-*] ', ln):
            p = doc.add_paragraph(style='List Bullet'); add_runs(p, ln[2:]); i += 1; continue
        # Leerzeile
        if not ln.strip():
            i += 1; continue
        # Absatz
        p = doc.add_paragraph(); add_runs(p, ln); i += 1

    doc.save(out_path)
    print("OK ->", out_path)

if __name__ == '__main__':
    build(sys.argv[1], sys.argv[2])
