"""Build the Vertex ERP user guide (PDF) from content.py and the screenshots in shots/."""
import os
import re
import sys

import arabic_reshaper
from bidi.algorithm import get_display

from PIL import Image as PILImage
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import mm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import (BaseDocTemplate, CondPageBreak, Frame, Image, KeepTogether, NextPageTemplate,
                                PageBreak, PageTemplate, Paragraph, Spacer, Table, TableStyle)
from reportlab.platypus.tableofcontents import TableOfContents

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from content import APPENDIX_ENTRIES, FAQ, GUIDE, SHORTCUTS  # noqa: E402

ROOT = "/Users/muhammeduvaise/Desktop/Vertex"
FONTS = os.path.join(ROOT, "vertex", "static", "fonts")
LOGO = os.path.join(ROOT, "vertex", "static", "brand", "vertex-logo.png")
OUT = os.path.join(ROOT, "docs", "Vertex-ERP-User-Guide.pdf")  # shots/ is next to this file
EDITION = "Edition 1.0 · November 2026"

pdfmetrics.registerFont(TTFont("Plex", os.path.join(FONTS, "IBMPlexSansArabic-Regular.ttf")))
pdfmetrics.registerFont(TTFont("Plex-Bold", os.path.join(FONTS, "IBMPlexSansArabic-Bold.ttf")))
pdfmetrics.registerFontFamily("Plex", normal="Plex", bold="Plex-Bold", italic="Plex", boldItalic="Plex-Bold")

BLUE = colors.HexColor("#1917FE")
INDIGO = colors.HexColor("#4f46e5")
INK = colors.HexColor("#0f1729")
TEXT = colors.HexColor("#273047")
MUTED = colors.HexColor("#6b7489")
LINE = colors.HexColor("#e3e6ef")
SOFT = colors.HexColor("#f5f6fb")
TINT = colors.HexColor("#eef0fe")
GREEN_T, GREEN = colors.HexColor("#e9f7ef"), colors.HexColor("#15803d")
AMBER_T, AMBER = colors.HexColor("#fff6e5"), colors.HexColor("#b45309")
RED_T, RED = colors.HexColor("#fdecec"), colors.HexColor("#b42318")

PAGE_W, PAGE_H = A4
M = 18 * mm
W = PAGE_W - 2 * M

st = {
    "body": ParagraphStyle("body", fontName="Plex", fontSize=9.6, leading=14.4, textColor=TEXT, spaceAfter=5),
    "small": ParagraphStyle("small", fontName="Plex", fontSize=8, leading=11, textColor=MUTED),
    "cap": ParagraphStyle("cap", fontName="Plex", fontSize=8, leading=11, textColor=MUTED, alignment=TA_CENTER, spaceBefore=3),
    "h1": ParagraphStyle("h1", fontName="Plex-Bold", fontSize=24, leading=29, textColor=INK, spaceAfter=4),
    "h1n": ParagraphStyle("h1n", fontName="Plex-Bold", fontSize=11, leading=14, textColor=BLUE),
    "intro": ParagraphStyle("intro", fontName="Plex", fontSize=11, leading=16.5, textColor=MUTED, spaceAfter=8),
    "h2": ParagraphStyle("h2", fontName="Plex-Bold", fontSize=13.5, leading=18, textColor=INK, spaceBefore=10, spaceAfter=5),
    "where": ParagraphStyle("where", fontName="Plex", fontSize=8.6, leading=12, textColor=INDIGO),
    "li": ParagraphStyle("li", fontName="Plex", fontSize=9.6, leading=14, textColor=TEXT),
    "num": ParagraphStyle("num", fontName="Plex-Bold", fontSize=9, leading=14, textColor=colors.white, alignment=TA_CENTER),
    "th": ParagraphStyle("th", fontName="Plex-Bold", fontSize=8.4, leading=11, textColor=INK),
    "td": ParagraphStyle("td", fontName="Plex", fontSize=8.6, leading=12, textColor=TEXT),
    "box": ParagraphStyle("box", fontName="Plex", fontSize=9, leading=13.2, textColor=TEXT),
    "boxh": ParagraphStyle("boxh", fontName="Plex-Bold", fontSize=8.4, leading=11, textColor=INK, spaceAfter=2),
    "toc1": ParagraphStyle("toc1", fontName="Plex-Bold", fontSize=10.5, leading=15, textColor=INK, spaceBefore=5),
    "toc2": ParagraphStyle("toc2", fontName="Plex", fontSize=9, leading=12.5, textColor=TEXT, leftIndent=14),
}


class Doc(BaseDocTemplate):
    def __init__(self, path):
        super().__init__(path, pagesize=A4, leftMargin=M, rightMargin=M, topMargin=22 * mm, bottomMargin=18 * mm,
                         title="Vertex ERP — User Guide", author="Vertex ERP", subject="User guide for customers")
        frame = Frame(M, 18 * mm, W, PAGE_H - 40 * mm, id="body", leftPadding=0, rightPadding=0, topPadding=0,
                      bottomPadding=0)
        cover = Frame(0, 0, PAGE_W, PAGE_H, id="cover", leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0)
        self.addPageTemplates([PageTemplate("cover", [cover], onPage=draw_cover),
                               PageTemplate("body", [frame], onPageEnd=draw_page)])
        self.chapter = ""

    def handle_documentBegin(self):
        self.chapter = ""
        super().handle_documentBegin()

    def afterFlowable(self, f):
        kind = getattr(f, "toc", None)
        if kind:
            level, text = kind
            if level == 0 and getattr(f, "running", True):
                self.chapter = getattr(f, "short", text)
            key = f"k{id(f)}"
            self.canv.bookmarkPage(key)
            self.canv.addOutlineEntry(text, key, level=level, closed=level == 0)
            self.notify("TOCEntry", (level, text, self.page, key))


def draw_cover(c, doc):
    c.saveState()
    c.setFillColor(colors.white)
    c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0)
    # a blue band at the foot and a soft panel behind the screenshot
    c.setFillColor(TINT)
    c.rect(0, 0, PAGE_W, PAGE_H * 0.46, fill=1, stroke=0)
    c.setFillColor(BLUE)
    c.rect(0, 0, PAGE_W, 9 * mm, fill=1, stroke=0)
    lw = 70 * mm
    with PILImage.open(LOGO) as im:
        lh = lw * im.height / im.width
    c.drawImage(LOGO, M, PAGE_H - 30 * mm - lh, width=lw, height=lh, mask="auto")
    c.setFillColor(INK)
    c.setFont("Plex-Bold", 34)
    c.drawString(M, PAGE_H - 78 * mm, "User Guide")
    c.setFont("Plex", 14)
    c.setFillColor(MUTED)
    c.drawString(M, PAGE_H - 89 * mm, "Accounting, operations and payroll — for every team")
    c.setFont("Plex", 10)
    c.drawString(M, PAGE_H - 98 * mm, EDITION)
    shot = os.path.join(HERE, "shots", "home.jpg")
    with PILImage.open(shot) as im:
        iw, ih = im.size
    sw = PAGE_W - 2 * M
    sh = sw * ih / iw
    sh = min(sh, 132 * mm)
    y = 24 * mm
    c.setFillColor(colors.HexColor("#d9dcf3"))
    c.roundRect(M - 1.2 * mm, y - 1.2 * mm, sw + 2.4 * mm, sh + 2.4 * mm, 3 * mm, fill=1, stroke=0)
    c.drawImage(shot, M, y, width=sw, height=sh, preserveAspectRatio=True, anchor="s")
    c.setFillColor(colors.white)
    c.setFont("Plex", 8)
    c.drawString(M, 3.4 * mm, "Vertex ERP  ·  User Guide")
    c.drawRightString(PAGE_W - M, 3.4 * mm, EDITION)
    c.restoreState()


def draw_page(c, doc):
    c.saveState()
    with PILImage.open(LOGO) as im:
        ratio = im.width / im.height
    lh = 5.2 * mm
    c.drawImage(LOGO, M, PAGE_H - 13 * mm, width=lh * ratio, height=lh, mask="auto")
    c.setFont("Plex", 8)
    c.setFillColor(MUTED)
    c.drawRightString(PAGE_W - M, PAGE_H - 11.6 * mm, f"User Guide  ·  {doc.chapter}" if doc.chapter else "User Guide")
    c.setStrokeColor(LINE)
    c.setLineWidth(0.6)
    c.line(M, PAGE_H - 16 * mm, PAGE_W - M, PAGE_H - 16 * mm)
    c.line(M, 12.5 * mm, PAGE_W - M, 12.5 * mm)
    c.drawString(M, 8.5 * mm, f"Vertex ERP  ·  {EDITION}")
    c.setFillColor(INK)
    c.setFont("Plex-Bold", 8.5)
    c.drawRightString(PAGE_W - M, 8.5 * mm, str(doc.page))
    c.restoreState()


AMP = re.compile(r"&(?!amp;|lt;|gt;|nbsp;|quot;|#)")
ARABIC_RUN = re.compile(r"[\u0600-\u06FF][\u0600-\u06FF\s]*[\u0600-\u06FF]|[\u0600-\u06FF]")


def clean(text):
    """Escape a bare & (so "P&L" is not read as an entity) and join Arabic words right to left."""
    text = AMP.sub("&amp;", text)
    return ARABIC_RUN.sub(lambda m: get_display(arabic_reshaper.reshape(m.group(0))), text)


def P(text, style="body"):
    return Paragraph(clean(text), st[style])


def heading(text, style, level, toc_text=None, running=True, short=None):
    para = P(text, style)
    para.toc = (level, toc_text or text)
    para.short = short or text
    para.running = running
    return para


def figure(name, caption, n):
    path = os.path.join(HERE, "shots", f"{name}.jpg")
    with PILImage.open(path) as im:
        iw, ih = im.size
    w = W
    h = w * ih / iw
    max_h = 125 * mm
    if h > max_h:
        h = max_h
        w = h * iw / ih
    img = Image(path, width=w, height=h)
    frame = Table([[img]], colWidths=[w + 2])
    frame.setStyle(TableStyle([("BOX", (0, 0), (-1, -1), 0.6, colors.HexColor("#d5d9e6")),
                               ("LEFTPADDING", (0, 0), (-1, -1), 1), ("RIGHTPADDING", (0, 0), (-1, -1), 1),
                               ("TOPPADDING", (0, 0), (-1, -1), 1), ("BOTTOMPADDING", (0, 0), (-1, -1), 1)]))
    frame.hAlign = "CENTER"
    return KeepTogether([Spacer(1, 3 * mm), frame, P(f"<b>Figure {n}</b>  ·  {caption}", "cap"), Spacer(1, 3 * mm)])


def callout(kind, text):
    label, bg, bar = {"tip": ("TIP", GREEN_T, GREEN), "note": ("NOTE", TINT, INDIGO),
                      "warn": ("IMPORTANT", AMBER_T, AMBER)}[kind]
    t = Table([["", [Paragraph(f'<font color="{bar.hexval()}">{label}</font>', st["boxh"]), P(text, "box")]]],
              colWidths=[1.6 * mm, W - 1.6 * mm])
    t.setStyle(TableStyle([("BACKGROUND", (0, 0), (0, 0), bar), ("BACKGROUND", (1, 0), (1, 0), bg),
                           ("LEFTPADDING", (1, 0), (1, 0), 9), ("RIGHTPADDING", (1, 0), (1, 0), 9),
                           ("TOPPADDING", (0, 0), (-1, -1), 6), ("BOTTOMPADDING", (0, 0), (-1, -1), 7)]))
    return KeepTogether([Spacer(1, 2 * mm), t, Spacer(1, 3 * mm)])


def entry_box(title, lines):
    rows = [[Paragraph(f'<font color="{INDIGO.hexval()}">ACCOUNTING ENTRY</font>  ·  {title}', st["boxh"]), "", ""]]
    for side, acc, note in lines:
        credit = side.startswith("Cr")
        rows.append([Paragraph(f"<b>{side}</b>", st["td"]),
                     Paragraph(("&nbsp;&nbsp;&nbsp;&nbsp;" if credit else "") + acc, st["td"]),
                     Paragraph(note, st["small"])])
    t = Table(rows, colWidths=[16 * mm, 88 * mm, W - 104 * mm])
    t.setStyle(TableStyle([("SPAN", (0, 0), (-1, 0)), ("BACKGROUND", (0, 0), (-1, -1), SOFT),
                           ("BOX", (0, 0), (-1, -1), 0.6, LINE), ("LINEBELOW", (0, 0), (-1, 0), 0.6, LINE),
                           ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("TOPPADDING", (0, 0), (-1, -1), 4),
                           ("BOTTOMPADDING", (0, 0), (-1, -1), 4), ("LEFTPADDING", (0, 0), (-1, -1), 8)]))
    return KeepTogether([Spacer(1, 2 * mm), t, Spacer(1, 3 * mm)])


def data_table(headers, rows, widths=None):
    widths = [W * w / sum(widths) for w in widths] if widths else [W / len(headers)] * len(headers)
    data = [[P(h, "th") for h in headers]] + [[P(str(c), "td") for c in r] for r in rows]
    t = Table(data, colWidths=widths, repeatRows=1)
    style = [("BACKGROUND", (0, 0), (-1, 0), TINT), ("LINEBELOW", (0, 0), (-1, 0), 1, INDIGO),
             ("VALIGN", (0, 0), (-1, -1), "TOP"), ("TOPPADDING", (0, 0), (-1, -1), 4),
             ("BOTTOMPADDING", (0, 0), (-1, -1), 4), ("LEFTPADDING", (0, 0), (-1, -1), 6),
             ("RIGHTPADDING", (0, 0), (-1, -1), 6)]
    for i in range(1, len(data)):
        style.append(("LINEBELOW", (0, i), (-1, i), 0.4, LINE))
        if i % 2 == 0:
            style.append(("BACKGROUND", (0, i), (-1, i), colors.HexColor("#fafbfd")))
    t.setStyle(TableStyle(style))
    return [Spacer(1, 2 * mm), t, Spacer(1, 4 * mm)]


def step_list(items):
    rows = []
    for i, s in enumerate(items, 1):
        badge = Table([[P(str(i), "num")]], colWidths=[6 * mm], rowHeights=[6 * mm])
        badge.setStyle(TableStyle([("BACKGROUND", (0, 0), (-1, -1), BLUE), ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
                                   ("LEFTPADDING", (0, 0), (-1, -1), 0), ("RIGHTPADDING", (0, 0), (-1, -1), 0),
                                   ("TOPPADDING", (0, 0), (-1, -1), 0), ("BOTTOMPADDING", (0, 0), (-1, -1), 0),
                                   ("ROUNDEDCORNERS", [3, 3, 3, 3])]))
        rows.append([badge, P(s, "li")])
    t = Table(rows, colWidths=[9 * mm, W - 9 * mm])
    t.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP"), ("LEFTPADDING", (0, 0), (-1, -1), 0),
                           ("TOPPADDING", (0, 0), (-1, -1), 2), ("BOTTOMPADDING", (0, 0), (-1, -1), 4)]))
    return [Spacer(1, 1 * mm), t, Spacer(1, 2 * mm)]


def bullet_list(items):
    def dot():
        d = Table([[""]], colWidths=[1.6 * mm], rowHeights=[1.6 * mm])
        d.setStyle(TableStyle([("BACKGROUND", (0, 0), (-1, -1), BLUE), ("ROUNDEDCORNERS", [0.8, 0.8, 0.8, 0.8])]))
        return d
    rows = [[dot(), P(s, "li")] for s in items]
    t = Table(rows, colWidths=[5 * mm, W - 5 * mm])
    t.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP"), ("LEFTPADDING", (0, 0), (-1, -1), 0),
                           ("TOPPADDING", (0, 0), (-1, -1), 1.5), ("BOTTOMPADDING", (0, 0), (-1, -1), 3),
                           ("TOPPADDING", (0, 0), (0, -1), 6.2)]))
    return [t, Spacer(1, 2 * mm)]


def where_chip(path):
    t = Table([[P(f"<b>Where:</b>  {path}", "where")]], hAlign="LEFT")
    t.setStyle(TableStyle([("BACKGROUND", (0, 0), (-1, -1), TINT), ("LEFTPADDING", (0, 0), (-1, -1), 8),
                           ("RIGHTPADDING", (0, 0), (-1, -1), 8), ("TOPPADDING", (0, 0), (-1, -1), 3),
                           ("BOTTOMPADDING", (0, 0), (-1, -1), 4), ("ROUNDEDCORNERS", [4, 4, 4, 4])]))
    return [t, Spacer(1, 3 * mm)]


def chapter_head(n, title, intro):
    band = Table([[""]], colWidths=[18 * mm], rowHeights=[1.6 * mm])
    band.setStyle(TableStyle([("BACKGROUND", (0, 0), (-1, -1), BLUE)]))
    band.hAlign = "LEFT"
    return [PageBreak(), Spacer(1, 6 * mm), band, Spacer(1, 4 * mm), P(f"CHAPTER {n}", "h1n"),
            heading(title, "h1", 0, f"{n}.  {title}"), P(intro, "intro"), Spacer(1, 2 * mm)]


def build():
    story = [NextPageTemplate("body"), PageBreak()]
    toc = TableOfContents()
    toc.levelStyles = [st["toc1"], st["toc2"]]
    toc.dotsMinLevel = 0
    story += [P("Contents", "h1"), Spacer(1, 4 * mm), toc]
    n_ch, n_fig = 0, 0
    for item in GUIDE:
        kind = item[0]
        if kind == "ch":
            n_ch += 1
            story += chapter_head(n_ch, item[1], item[2])
        elif kind == "sec":
            story += [CondPageBreak(40 * mm), heading(item[1], "h2", 1)]
        elif kind == "p":
            story.append(P(item[1]))
        elif kind == "where":
            story += where_chip(item[1])
        elif kind == "steps":
            story += step_list(item[1])
        elif kind == "bullets":
            story += bullet_list(item[1])
        elif kind == "shot":
            n_fig += 1
            story.append(figure(item[1], item[2], n_fig))
        elif kind == "entry":
            story.append(entry_box(item[1], item[2]))
        elif kind in ("tip", "note", "warn"):
            story.append(callout(kind, item[1]))
        elif kind == "table":
            story += data_table(item[1], item[2], item[3])
    # appendices
    story += [PageBreak(), Spacer(1, 6 * mm), P("APPENDIX A", "h1n"),
              heading("Accounting entries reference", "h1", 0, "A.  Accounting entries reference", short="Appendices"),
              P("The entry Vertex posts for each document, in one place. Amounts are in the branch currency.", "intro")]
    story += data_table(["Document or event", "Debit", "Credit"], [list(r) for r in APPENDIX_ENTRIES], [62, 59, 59])
    story += [CondPageBreak(60 * mm), P("APPENDIX B", "h1n"), heading("Keyboard shortcuts", "h2", 0, "B.  Keyboard shortcuts", running=False)]
    story += data_table(["Keys", "What they do"], [list(r) for r in SHORTCUTS], [55, 125])
    story += [CondPageBreak(60 * mm), P("APPENDIX C", "h1n"), heading("Frequently asked questions", "h2", 0, "C.  Frequently asked questions", running=False)]
    for q, a in FAQ:
        story.append(KeepTogether([P(f"<b>{q}</b>", "body"), P(a, "body"), Spacer(1, 1.5 * mm)]))
    story += [Spacer(1, 8 * mm), callout("note", "Need help? Contact your Vertex administrator or your Vertex partner. "
                                                 "Screens in this guide are from the demo company and may differ slightly "
                                                 "from your version.")]
    os.makedirs(os.path.dirname(OUT), exist_ok=True)
    doc = Doc(OUT)
    doc.multiBuild(story)
    print(OUT, os.path.getsize(OUT) // 1024, "KB", "figures", n_fig)


if __name__ == "__main__":
    build()
