"""
md_to_pdf.py — Markdown to DIN A4 PDF converter using reportlab
Usage: python3 scripts/md_to_pdf.py my_inbox/neandertal_museum_kurzinfo.md
"""
import sys
import re
from pathlib import Path
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import cm
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_LEFT, TA_CENTER
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, HRFlowable
)
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

# Color palette
C_DARK   = colors.HexColor("#1a1a2e")
C_BLUE   = colors.HexColor("#2c5f6e")
C_TEAL   = colors.HexColor("#4a90a4")
C_LIGHT  = colors.HexColor("#f5f9fa")
C_GRAY   = colors.HexColor("#555555")
C_BORDER = colors.HexColor("#dddddd")

def make_styles():
    return {
        "h1": ParagraphStyle("h1", fontName="Helvetica-Bold", fontSize=16,
                              textColor=C_DARK, spaceAfter=4, spaceBefore=0),
        "h2": ParagraphStyle("h2", fontName="Helvetica-Bold", fontSize=9,
                              textColor=C_BLUE, spaceAfter=2, spaceBefore=6,
                              textTransform="uppercase"),
        "body": ParagraphStyle("body", fontName="Helvetica", fontSize=9,
                               textColor=colors.HexColor("#222222"),
                               leading=13, spaceAfter=2),
        "meta": ParagraphStyle("meta", fontName="Helvetica-Oblique", fontSize=8,
                               textColor=C_GRAY, spaceAfter=4),
        "li":   ParagraphStyle("li", fontName="Helvetica", fontSize=9,
                               textColor=colors.HexColor("#222222"),
                               leading=13, leftIndent=12, spaceAfter=1),
        "note": ParagraphStyle("note", fontName="Helvetica-Oblique", fontSize=7.5,
                               textColor=C_GRAY, spaceAfter=0),
    }


def parse_md(md_text: str, styles: dict) -> list:
    elements = []
    lines = md_text.splitlines()
    i = 0

    def bold(t):
        t = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', t)
        t = re.sub(r'\*(.+?)\*',     r'<i>\1</i>', t)
        return t

    while i < len(lines):
        line = lines[i].rstrip()

        # Skip horizontal rules visually (add small spacer)
        if re.match(r'^---+$', line):
            elements.append(HRFlowable(width="100%", thickness=0.5,
                                       color=C_BORDER, spaceAfter=3, spaceBefore=1))
            i += 1
            continue

        # H1
        if line.startswith('# '):
            elements.append(Paragraph(line[2:], styles["h1"]))
            i += 1
            continue

        # H2
        if line.startswith('## '):
            elements.append(Paragraph(line[3:].upper(), styles["h2"]))
            i += 1
            continue

        # Table: collect all table lines
        if line.startswith('|'):
            table_lines = []
            while i < len(lines) and lines[i].strip().startswith('|'):
                table_lines.append(lines[i])
                i += 1
            # Filter separator rows
            rows = [r for r in table_lines if not re.match(r'^\|[-| :]+\|$', r.strip())]
            data = []
            for row in rows:
                cells = [c.strip() for c in row.strip('|').split('|')]
                data.append(cells)
            if data:
                col_widths = [5.5*cm, 11.5*cm] if len(data[0]) == 2 else None
                t = Table(data, colWidths=col_widths, hAlign='LEFT')
                ts = TableStyle([
                    ('FONTNAME',    (0,0), (-1,-1), 'Helvetica'),
                    ('FONTSIZE',    (0,0), (-1,-1), 8.5),
                    ('FONTNAME',    (0,0), (0,-1),  'Helvetica-Bold'),
                    ('TEXTCOLOR',   (0,0), (0,-1),  C_BLUE),
                    ('TEXTCOLOR',   (1,0), (1,-1),  colors.HexColor("#222222")),
                    ('ROWBACKGROUNDS', (0,0), (-1,-1), [colors.white, C_LIGHT]),
                    ('GRID',        (0,0), (-1,-1), 0.4, C_BORDER),
                    ('TOPPADDING',  (0,0), (-1,-1), 3),
                    ('BOTTOMPADDING', (0,0), (-1,-1), 3),
                    ('LEFTPADDING', (0,0), (-1,-1), 6),
                    ('VALIGN',      (0,0), (-1,-1), 'TOP'),
                ])
                t.setStyle(ts)
                elements.append(t)
                elements.append(Spacer(1, 4))
            continue

        # Ordered list
        if re.match(r'^\d+\. ', line):
            num = 1
            while i < len(lines) and re.match(r'^\d+\. ', lines[i]):
                text = re.sub(r'^\d+\. ', '', lines[i])
                elements.append(Paragraph(f"{num}. {bold(text)}", styles["li"]))
                num += 1
                i += 1
            continue

        # Unordered list
        if re.match(r'^[-*] ', line):
            while i < len(lines) and re.match(r'^[-*] ', lines[i]):
                text = re.sub(r'^[-*] ', '', lines[i])
                elements.append(Paragraph(f"• {bold(text)}", styles["li"]))
                i += 1
            continue

        # Italic meta line (e.g. *Erstellt: ...*)
        if re.match(r'^\*.+\*$', line):
            elements.append(Paragraph(line.strip('*'), styles["meta"]))
            i += 1
            continue

        # Note line (starts with *Hinweis*)
        if line.startswith('*Hinweis') or line.startswith('*Note'):
            elements.append(Paragraph(line.strip('*'), styles["note"]))
            i += 1
            continue

        # Empty line → small spacer
        if not line.strip():
            elements.append(Spacer(1, 2))
            i += 1
            continue

        # Regular paragraph
        elements.append(Paragraph(bold(line), styles["body"]))
        i += 1

    return elements


def convert(md_path: str):
    md = Path(md_path).read_text(encoding="utf-8")

    # Remove "Quellen" section for cleaner one-pager
    md = re.sub(r'\n## Quellen[\s\S]*', '', md)

    out_path = str(Path(md_path).with_suffix('.pdf'))
    doc = SimpleDocTemplate(
        out_path, pagesize=A4,
        leftMargin=1.6*cm, rightMargin=1.6*cm,
        topMargin=1.4*cm, bottomMargin=1.4*cm,
    )
    styles = make_styles()
    elements = parse_md(md, styles)
    doc.build(elements)
    print(f"PDF saved: {out_path}")


if __name__ == "__main__":
    convert(sys.argv[1] if len(sys.argv) > 1 else "my_inbox/neandertal_museum_kurzinfo.md")
