#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Genera PDF del briefing integral para letrada (ReportLab)."""
import re
from pathlib import Path
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY, TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import cm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak, HRFlowable,
)

SRC = Path(__file__).parent / "05_briefing_integral_letrada_garcia.md"
OUT = Path(__file__).parent / "05_briefing_integral_letrada_garcia.pdf"
FONT = "ArialUnicode"
FONT_B = "ArialUnicode-Bold"
FONT_I = "ArialUnicode-Italic"


def register_fonts():
    import os
    fonts = os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts")
    pdfmetrics.registerFont(TTFont(FONT, fonts + r"\arial.ttf"))
    pdfmetrics.registerFont(TTFont(FONT_B, fonts + r"\arialbd.ttf"))
    pdfmetrics.registerFont(TTFont(FONT_I, fonts + r"\ariali.ttf"))


def esc(text: str) -> str:
    return (
        text.replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
    )


def md_inline(text: str) -> str:
    text = esc(text)
    text = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", text)
    text = re.sub(r"`(.+?)`", r"<font face='Courier'>\1</font>", text)
    text = re.sub(r"\[(.+?)\]\(.+?\)", r"\1", text)
    return text


def styles():
    return {
        "title": ParagraphStyle("title", fontName=FONT_B, fontSize=14, leading=18, alignment=TA_CENTER, spaceAfter=12),
        "h1": ParagraphStyle("h1", fontName=FONT_B, fontSize=12, leading=15, spaceBefore=14, spaceAfter=8, textColor=colors.HexColor("#1a365d")),
        "h2": ParagraphStyle("h2", fontName=FONT_B, fontSize=10.5, leading=13, spaceBefore=10, spaceAfter=6, textColor=colors.HexColor("#2c5282")),
        "h3": ParagraphStyle("h3", fontName=FONT_B, fontSize=9.5, leading=12, spaceBefore=8, spaceAfter=4),
        "body": ParagraphStyle("body", fontName=FONT, fontSize=9, leading=12, alignment=TA_JUSTIFY, spaceAfter=4),
        "quote": ParagraphStyle("quote", fontName=FONT_I, fontSize=9, leading=12, leftIndent=12, borderPadding=4, spaceAfter=6, textColor=colors.HexColor("#333333")),
        "li": ParagraphStyle("li", fontName=FONT, fontSize=9, leading=12, leftIndent=14, bulletIndent=6, spaceAfter=2),
        "small": ParagraphStyle("small", fontName=FONT, fontSize=8, leading=10, textColor=colors.grey),
    }


def parse_table(lines):
    rows = []
    for line in lines:
        if not line.strip().startswith("|"):
            break
        cells = [c.strip() for c in line.strip().strip("|").split("|")]
        if all(re.match(r"^[-:]+$", c.replace(" ", "")) for c in cells):
            continue
        rows.append([md_inline(c) for c in cells])
    return rows


def build():
    register_fonts()
    st = styles()
    text = SRC.read_text(encoding="utf-8")
    lines = text.splitlines()
    story = []
    i = 0
    in_code = False

    story.append(Paragraph(md_inline("BRIEFING INTEGRAL PARA LETRADA"), st["title"]))
    story.append(Paragraph(md_inline("D.ª Rosa María García Ros (ICAV) — Cliente: Diego Martínez Saiz"), st["body"]))
    story.append(Spacer(1, 0.3 * cm))
    story.append(HRFlowable(width="100%", thickness=1, color=colors.HexColor("#cbd5e0")))
    story.append(Spacer(1, 0.3 * cm))

    while i < len(lines):
        line = lines[i]
        raw = line.rstrip()

        if raw.startswith("```"):
            in_code = not in_code
            i += 1
            continue
        if in_code:
            story.append(Paragraph(f"<font face='Courier' size='8'>{esc(raw)}</font>", st["body"]))
            i += 1
            continue

        if not raw.strip():
            i += 1
            continue

        if raw.startswith("# "):
            story.append(PageBreak() if len(story) > 10 and raw.startswith("# ") and i > 50 else Spacer(1, 0))
            story.append(Paragraph(md_inline(raw[2:]), st["h1"]))
            i += 1
            continue
        if raw.startswith("## "):
            story.append(Paragraph(md_inline(raw[3:]), st["h2"]))
            i += 1
            continue
        if raw.startswith("### "):
            story.append(Paragraph(md_inline(raw[4:]), st["h3"]))
            i += 1
            continue

        if raw.startswith("> "):
            quote_lines = []
            while i < len(lines) and lines[i].startswith(">"):
                quote_lines.append(lines[i][2:].strip())
                i += 1
            story.append(Paragraph(md_inline(" ".join(quote_lines)), st["quote"]))
            continue

        if raw.startswith("|"):
            table_lines = []
            while i < len(lines) and lines[i].strip().startswith("|"):
                table_lines.append(lines[i])
                i += 1
            rows = parse_table(table_lines)
            if rows:
                col_n = len(rows[0])
                w = (16.5 * cm) / col_n
                t = Table(rows, colWidths=[w] * col_n, repeatRows=1)
                t.setStyle(TableStyle([
                    ("FONTNAME", (0, 0), (-1, 0), FONT_B),
                    ("FONTNAME", (0, 1), (-1, -1), FONT),
                    ("FONTSIZE", (0, 0), (-1, -1), 7.5),
                    ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#e2e8f0")),
                    ("GRID", (0, 0), (-1, -1), 0.25, colors.grey),
                    ("VALIGN", (0, 0), (-1, -1), "TOP"),
                    ("LEFTPADDING", (0, 0), (-1, -1), 3),
                    ("RIGHTPADDING", (0, 0), (-1, -1), 3),
                ]))
                story.append(t)
                story.append(Spacer(1, 0.2 * cm))
            continue

        if raw.startswith("- ") or raw.startswith("* "):
            story.append(Paragraph(f"• {md_inline(raw[2:])}", st["li"]))
            i += 1
            continue

        if re.match(r"^\d+\.\s", raw):
            story.append(Paragraph(md_inline(raw), st["li"]))
            i += 1
            continue

        if raw.startswith("---"):
            story.append(Spacer(1, 0.2 * cm))
            story.append(HRFlowable(width="100%", thickness=0.5, color=colors.lightgrey))
            i += 1
            continue

        story.append(Paragraph(md_inline(raw), st["body"]))
        i += 1

    doc = SimpleDocTemplate(
        str(OUT), pagesize=A4,
        leftMargin=2 * cm, rightMargin=2 * cm, topMargin=2 * cm, bottomMargin=2 * cm,
        title="Briefing integral letrada - Diego M. Saiz",
        author="Expediente 658/2023",
    )
    doc.build(story)
    print(f"PDF generado: {OUT}")


if __name__ == "__main__":
    build()
