# ============================================================
# ADDITIVE: letterhead PDF renderer for the Document & Letter Issuance Center.
#
# Layout copied from the company's own letters: logo top-right, optional company block (name, CIN, registered
# office) and rule, centred title, justified body, stamp + signature, footer with company name / address / CIN / URL
# on EVERY page.  The text of a letter is a tiny markup (documented in MARKUP_HELP) so each company can change it.
# ============================================================
import re
from io import BytesIO
from xml.sax.saxutils import escape

from django.conf import settings
from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY, TA_LEFT, TA_RIGHT
from reportlab.lib.pagesizes import A4, LETTER
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import mm
from reportlab.lib.utils import ImageReader, simpleSplit
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import (BaseDocTemplate, Flowable, Frame, Image, KeepTogether, PageBreak, PageTemplate,
                                Paragraph, Spacer, Table, TableStyle)

MONTHS = "January|February|March|April|May|June|July|August|September|October|November|December"
ORD_RE = re.compile(rf"\b(\d{{1,2}}) ({MONTHS}) (\d{{4}})\b")
DIRECTIVE = re.compile(r"^\[\[(/?[a-z_]+)(?::([^\]]*))?\]\]$")
COND = re.compile(r"^\[\[(if|ifnot) ([A-Za-z_][A-Za-z0-9_]*)\]\]$")

MARKUP_HELP = {
    "paragraphs": "A blank line starts a new paragraph. Lines inside a paragraph are kept as separate lines.",
    "prefixes": {"# text": "centred bold underlined title", "#~ text": "centred bold title without underline", "## text": "centred underlined sub-title",
                 "### text": "bold heading (left)", ">> text": "right aligned (e.g. the date)",
                 ".. text": "left aligned (not justified)", "- text": "bullet point"},
    "inline": {"**text**": "bold", "++text++": "underline"},
    "directives": {"[[space:N]]": "vertical space of N mm", "[[line:N]]": "short horizontal line, N mm long",
                   "[[stampsign]]": "company stamp + signature image (from the letterhead settings)",
                   "[[pagebreak]]": "start a new page", "[[keep]] ... [[/keep]]": "keep these lines on one page",
                   "[[ordinal_dates]]": "show 24 April 2026 as 24th April 2026 (superscript) in the whole letter",
                   "[[header:full]] / [[header:logo]] / [[header:none]]": "choose this letter's header (company block + line, logo only, nothing)",
                   "[[if name]] ... [[endif]]": "print the lines only when the placeholder has a value",
                   "[[ifnot name]] ... [[endif]]": "print the lines only when the placeholder is empty"},
    "placeholders": "Any {placeholder} from GET /api/people/letter-center/variables/ , e.g. {employee_name} {designation} {date}.",
}

# ------------------------------------------------------------------ fonts
_FONT_CANDIDATES = [   # (regular, bold, scale)  scale = size correction against Calibri
    ("/usr/share/fonts/truetype/crosextra/Carlito-Regular.ttf", "/usr/share/fonts/truetype/crosextra/Carlito-Bold.ttf", 1.0),
    ("C:/Windows/Fonts/calibri.ttf", "C:/Windows/Fonts/calibrib.ttf", 1.0),
    ("/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", 0.95),
    ("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 0.88),
    ("/System/Library/Fonts/Supplemental/Arial.ttf", "/System/Library/Fonts/Supplemental/Arial Bold.ttf", 0.95),
]
_cache = {}


def fonts():
    """(regular_name, bold_name, scale, has_rupee). Registers a TrueType family when one is installed."""
    if "f" in _cache:
        return _cache["f"]
    import os
    cands = list(_FONT_CANDIDATES)
    reg, bold = getattr(settings, "LETTER_FONT_REGULAR", None), getattr(settings, "LETTER_FONT_BOLD", None)
    if reg and bold:
        cands.insert(0, (reg, bold, 1.0))
    for i, (r, b, scale) in enumerate(cands):
        if os.path.exists(r) and os.path.exists(b):
            try:
                pdfmetrics.registerFont(TTFont(f"LH-Reg{i}", r))
                pdfmetrics.registerFont(TTFont(f"LH-Bold{i}", b))
                pdfmetrics.registerFontFamily(f"LH-Reg{i}", normal=f"LH-Reg{i}", bold=f"LH-Bold{i}",
                                              italic=f"LH-Reg{i}", boldItalic=f"LH-Bold{i}")
                has = 0x20B9 in pdfmetrics.getFont(f"LH-Reg{i}").face.charToGlyph
                _cache["f"] = (f"LH-Reg{i}", f"LH-Bold{i}", scale, has)
                return _cache["f"]
            except Exception:                                   # noqa: BLE001 - try the next candidate
                continue
    _cache["f"] = ("Helvetica", "Helvetica-Bold", 1.0, False)
    return _cache["f"]


def currency_symbol():
    """The rupee sign when the PDF font can draw it, otherwise 'Rs. '."""
    return "\u20b9" if fonts()[3] else "Rs. "


# ------------------------------------------------------------------ text helpers
def ordinal_suffix(n):
    n = int(n)
    return "th" if 10 <= n % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")


def inline(text, ordinal_dates=False):
    t = escape(text)
    t = re.sub(rf"\b0(\d) ({MONTHS})\b", r"\1 \2", t)               # 01 April -> 1 April
    if ordinal_dates:
        t = ORD_RE.sub(lambda m: f"{m.group(1)}<super>{ordinal_suffix(m.group(1))}</super> {m.group(2)} {m.group(3)}", t)
    t = t.replace("\u2060", "")                                         # word-joiner used to keep a date 'plain'
    t = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", t)
    t = re.sub(r"\+\+(.+?)\+\+", r"<u>\1</u>", t)
    return t


def apply_conditionals(text, variables):
    """Resolve [[if x]] / [[ifnot x]] ... [[endif]] using the given values (idempotent)."""
    out, stack = [], []
    for line in text.replace("\r\n", "\n").split("\n"):
        m = COND.match(line.strip())
        if m:
            val = str((variables or {}).get(m.group(2), "") or "").strip()
            truthy = val not in ("", "-", "None")
            stack.append(truthy if m.group(1) == "if" else not truthy)
            continue
        if line.strip() == "[[endif]]":
            if stack:
                stack.pop()
            continue
        if all(stack):
            out.append(line)
    return "\n".join(out)


def plain_text(body):
    """The letter without markup (for previews / e-mail)."""
    keep = []
    for line in (body or "").replace("\r\n", "\n").split("\n"):
        s = line.strip()
        if DIRECTIVE.match(s) or COND.match(s) or s == "[[endif]]":
            continue
        s = re.sub(r"^(#{1,3}|#~|>>|\.\.|-) ", lambda m: "- " if m.group(1) == "-" else "", s)
        s = s.replace("**", "").replace("++", "")
        keep.append(s)
    return re.sub(r"\n{3,}", "\n\n", "\n".join(keep)).strip()


class HLine(Flowable):
    def __init__(self, width_mm):
        super().__init__()
        self.w = width_mm * mm
        self.width, self.height = self.w, 2

    def draw(self):
        self.canv.setLineWidth(0.7)
        self.canv.line(0, 1, self.w, 1)


# ------------------------------------------------------------------ letterhead context
def _bytes(f):
    try:
        if f and getattr(f, "name", None):
            with f.open("rb") as fh:
                return fh.read()
    except Exception:                                           # noqa: BLE001
        pass
    return None


def _trim(data):
    """Crop transparent / white borders of a stamp or signature so it prints at its real size."""
    try:
        from PIL import Image, ImageChops
        im = Image.open(BytesIO(data))
        if im.mode in ("RGBA", "LA"):
            bbox = im.getchannel("A").getbbox()
        else:
            rgb = im.convert("RGB")
            bbox = ImageChops.difference(rgb, Image.new("RGB", rgb.size, (255, 255, 255))).getbbox()
        if not bbox:
            return data
        out = BytesIO()
        im.crop(bbox).save(out, format="PNG")
        return out.getvalue()
    except Exception:                                           # noqa: BLE001 - keep the original image
        return data


def letterhead_context(company):
    """Everything the page header / footer / signature needs. Blank letterhead fields fall back to the company master."""
    from .models import CompanyLetterhead
    lh = CompanyLetterhead.objects.filter(company=company).first()

    def pick(own, *fallbacks):
        for v in (own, *fallbacks):
            if v and str(v).strip():
                return str(v).strip()
        return ""
    legal = pick(getattr(lh, "legal_name", ""), company.Registered_Company_Name, company.Brand_Name)
    office = pick(getattr(lh, "registered_office", ""), company.REGISTERED_OFFICE_add, company.Company_address)
    ctx = {
        "legal_name": legal, "footer_name": pick(getattr(lh, "footer_name", ""), legal.upper()),
        "short_name": pick(getattr(lh, "short_name", ""), company.Registered_Company_Name, company.Brand_Name, legal),
        "cin": pick(getattr(lh, "cin", "")), "website": pick(getattr(lh, "website", ""), company.Website),
        "registered_office": office, "footer_address": pick(getattr(lh, "footer_address", ""), office),
        "place": pick(getattr(lh, "place", "")),
        "signatory_name": pick(getattr(lh, "signatory_name", "")),
        "signatory_title": pick(getattr(lh, "signatory_title", ""), "Authorized Signatory"),
        "header_style": getattr(lh, "header_style", "FULL"), "footer_enabled": getattr(lh, "footer_enabled", True),
        "page_size": getattr(lh, "page_size", "A4"), "font_size": getattr(lh, "body_font_size", 11) or 11,
        "show_ref_no": getattr(lh, "show_ref_no", False),
        "logo": _bytes(getattr(lh, "logo", None)) or _bytes(getattr(company, "Company_logo", None)),
        "stamp": _trim(_bytes(getattr(lh, "stamp", None)) or b"") if _bytes(getattr(lh, "stamp", None)) else None,
        "signature": _trim(_bytes(getattr(lh, "signature", None)) or b"") if _bytes(getattr(lh, "signature", None)) else None,
        "policy": {**{"probation_months": 3, "notice_probation_days": 7, "notice_confirmed_days": 30,
                      "leave_in_probation_days": 2, "salary_disbursal": "1st to 10th of every month",
                      "employment_status": "Full-time"}, **(getattr(lh, "policy_defaults", None) or {})},
    }
    return ctx


def _image(data, max_w_mm, max_h_mm):
    """reportlab Image scaled into a box, or None when the bytes are not an image."""
    try:
        ir = ImageReader(BytesIO(data))
        w, h = ir.getSize()
        k = min(max_w_mm * mm / w, max_h_mm * mm / h)
        return Image(BytesIO(data), width=w * k, height=h * k, mask="auto")
    except Exception:                                           # noqa: BLE001
        return None


# ------------------------------------------------------------------ the renderer
def render_letter_pdf(ctx, subject, body, variables=None, letter_no="", title=None):
    reg, bold, scale, _ = fonts()
    pagesize = LETTER if ctx["page_size"] == "LETTER" else A4
    W, H = pagesize
    lm = rm = 22 * mm
    fs = max(8, min(14, ctx["font_size"])) * scale
    style = lambda name, **kw: ParagraphStyle(name, fontName=kw.pop("fontName", reg), fontSize=kw.pop("fontSize", fs),
                                              leading=kw.pop("leading", fs * 1.32), **kw)
    S = {"body": style("body", alignment=TA_JUSTIFY, spaceAfter=fs * 0.55),
         "left": style("left", alignment=TA_LEFT, spaceAfter=fs * 0.55),
         "right": style("right", alignment=TA_RIGHT, spaceAfter=fs * 0.55),
         "title": style("title", fontName=bold, fontSize=fs * 1.3, alignment=TA_CENTER, spaceBefore=fs * 0.3, spaceAfter=fs * 0.7),
         "sub": style("sub", alignment=TA_CENTER, fontSize=fs * 0.95, spaceAfter=fs * 1.0),
         "heading": style("heading", fontName=bold, alignment=TA_LEFT, spaceBefore=fs * 0.6, spaceAfter=fs * 0.35),
         "bullet": style("bullet", alignment=TA_JUSTIFY, leftIndent=fs * 1.6, bulletIndent=fs * 0.5, spaceAfter=fs * 0.2)}

    header_style = ctx["header_style"]
    m_h = re.search(r"^\[\[header:(full|logo|none)\]\]\s*$", body or "", re.M)      # a letter can choose its own header
    if m_h:
        header_style = {"full": "FULL", "logo": "LOGO_ONLY", "none": "NONE"}[m_h.group(1)]
    office_w = W - lm - rm
    office_lines = simpleSplit("Registered Office " + (ctx["registered_office"] or ""), reg, 9 * scale, office_w) if ctx["registered_office"] else []
    header_h = {"FULL": 44 + 4.3 * len(office_lines), "LOGO_ONLY": 33, "NONE": 16}[header_style] * mm
    foot_lines = simpleSplit((ctx["footer_address"] or "").replace("\n", " "), reg, 8.5 * scale, office_w) if ctx["footer_address"] else []
    footer_h = (14 + 3.9 * (len(foot_lines) + 1 + (1 if (ctx["cin"] or ctx["website"]) else 0))) * mm if ctx["footer_enabled"] else 14 * mm

    logo = ctx["logo"]

    def decorate(canv, doc):
        canv.saveState()
        top = H - 12 * mm
        if logo and header_style != "NONE":
            img = _image(logo, 52, 15)
            if img is not None:
                canv.drawImage(ImageReader(BytesIO(logo)), W - rm - img.drawWidth, top - img.drawHeight,
                               width=img.drawWidth, height=img.drawHeight, mask="auto")
        if header_style == "FULL":
            y = H - 22 * mm
            canv.setFont(bold, 12.5 * scale)
            canv.drawString(lm, y, (ctx["legal_name"] or "").upper())
            y -= 5 * mm
            if ctx["cin"]:
                canv.setFont(bold, 9 * scale)
                canv.drawString(lm, y, "CIN:")
                canv.setFont(reg, 9 * scale)
                canv.drawString(lm + canv.stringWidth("CIN:", bold, 9 * scale) + 1, y, ctx["cin"])
            y -= 8 * mm
            if office_lines:
                canv.setFont(bold, 9 * scale)
                canv.drawString(lm, y, "Registered Office")
                first = office_lines[0][len("Registered Office"):].lstrip()
                canv.setFont(reg, 9 * scale)
                canv.drawString(lm + canv.stringWidth("Registered Office ", bold, 9 * scale), y, first)
                for ln in office_lines[1:]:
                    y -= 4.3 * mm
                    canv.drawString(lm, y, ln)
            y -= 4 * mm
            canv.setLineWidth(1.6)
            canv.line(lm, y, W - rm, y)
        if ctx["footer_enabled"]:
            y = 12 * mm + (len(foot_lines) + 1 + (1 if (ctx["cin"] or ctx["website"]) else 0)) * 3.9 * mm
            canv.setLineWidth(1.4)
            canv.line(lm, y + 3 * mm, W - rm, y + 3 * mm)
            canv.setFont(bold, 9 * scale)
            canv.drawString(lm, y - 1 * mm, ctx["footer_name"] or "")
            canv.setFont(reg, 8.5 * scale)
            yy = y - 5 * mm
            for ln in foot_lines:
                canv.drawString(lm, yy, ln)
                yy -= 3.9 * mm
            if ctx["cin"] or ctx["website"]:
                yy -= 2.5 * mm
                canv.setFont(reg, 8.5 * scale)
                canv.drawString(lm, yy, f"CIN# {ctx['cin']}" if ctx["cin"] else "")
                if ctx["website"]:
                    canv.drawString(lm + 78 * mm, yy, f"URL : {ctx['website']}")
        canv.restoreState()

    buf = BytesIO()
    doc = BaseDocTemplate(buf, pagesize=pagesize, title=title or subject or "Letter", author=ctx["legal_name"] or "")
    frame = Frame(lm, footer_h + 3 * mm, W - lm - rm, H - header_h - footer_h - 3 * mm, leftPadding=0, rightPadding=0,
                  topPadding=2 * mm, bottomPadding=0, id="body")
    doc.addPageTemplates([PageTemplate(id="letter", frames=[frame], onPage=decorate)])

    story = _story(apply_conditionals(body or "", variables), S, ctx, bold, fs, W - lm - rm, letter_no)
    doc.build(story)
    return buf.getvalue()


def _stamp_sign(ctx):
    cells = []
    for key, w, h in (("stamp", 30, 30), ("signature", 28, 13)):
        img = _image(ctx[key], w, h) if ctx.get(key) else None
        if img is not None:
            cells.append(img)
    if not cells:
        return Spacer(1, 16 * mm)
    if len(cells) == 1:
        return cells[0] if False else Table([[cells[0]]], colWidths=[cells[0].drawWidth], hAlign="LEFT")
    t = Table([[cells[0]], [cells[1]]], colWidths=[max(c.drawWidth for c in cells)], hAlign="LEFT")
    t.setStyle(TableStyle([("LEFTPADDING", (0, 0), (-1, -1), 0), ("TOPPADDING", (0, 0), (-1, -1), 1),
                           ("BOTTOMPADDING", (0, 0), (-1, -1), 1)]))
    return t


def _story(text, S, ctx, bold_name, fs, width, letter_no):
    story, buf, keep, in_keep = [], [], [], False
    ordinal = False

    def emit(flow):
        (keep if in_keep else story).append(flow)

    def flush():
        nonlocal buf
        if not buf:
            return
        lines = buf
        buf = []
        kind = "body"
        first = lines[0]
        for prefix, k in (("### ", "heading"), ("## ", "sub"), ("#~ ", "titleplain"), ("# ", "title"), (">> ", "right"), (".. ", "left")):
            if first.startswith(prefix):
                kind = k
                lines = [first[len(prefix):]] + lines[1:]
                break
        if kind in ("title", "titleplain", "sub", "heading"):      # only the first line carries the heading style
            txt = inline(lines[0], ordinal)
            emit(Paragraph(txt if kind in ("heading", "titleplain") else f"<u>{txt}</u>", S["title" if kind == "titleplain" else kind]))
            lines, kind = lines[1:], "body"
        group = []

        def close():
            nonlocal group
            if group:
                emit(Paragraph("<br/>".join(inline(l, ordinal) for l in group), S[kind]))
                group = []
        for ln in lines:
            if ln.startswith("- "):
                close()
                emit(Paragraph(inline(ln[2:], ordinal), S["bullet"], bulletText="\u2022"))
            else:
                group.append(ln)
        close()

    for raw in text.replace("\r\n", "\n").split("\n"):
        line = raw.strip()
        m = DIRECTIVE.match(line)
        if m:
            name, arg = m.group(1), m.group(2)
            if name == "ordinal_dates":
                ordinal = True
                continue
            if name == "header":
                continue
            flush()
            if name == "space":
                emit(Spacer(1, float(arg or 6) * mm))
            elif name == "line":
                emit(HLine(float(arg or 40)))
            elif name == "stampsign":
                emit(_stamp_sign(ctx))
            elif name == "pagebreak":
                emit(PageBreak())
            elif name == "keep":
                in_keep = True
            elif name == "/keep":
                in_keep = False
                if keep:
                    story.append(KeepTogether(keep))
                keep = []
            continue
        if not line:
            flush()
            continue
        if buf and re.match(r"^(#{1,3}|#~|>>|\.\.) ", line):         # a new heading / right / left line starts a new paragraph
            flush()
        buf.append(line)
    flush()
    if keep:
        story.append(KeepTogether(keep))
    if ctx.get("show_ref_no") and letter_no:
        story.insert(0, Paragraph(f"Ref: {escape(letter_no)}", S["left"]))
    return story
