#!/usr/bin/env python3
"""Build clickable branded PDF deliverable for Portal Confraria Brasil."""
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm, mm
from reportlab.lib.colors import Color, HexColor, white
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import os

# Brand palette (manual Velos)
CREAM = HexColor("#F5F7F1")
NAVY  = HexColor("#001226")
GOLD  = HexColor("#A68A58")
GOLD_LIGHT = HexColor("#C8AF7D")
LINE  = HexColor("#D8D8C8")
SOFT  = HexColor("#6A6A5E")

# Fonts — register serifs that exist on this system
for face, ttf in [
    ("SerifBold", "/usr/share/fonts/truetype/liberation/LiberationSerif-Bold.ttf"),
    ("SerifItalic", "/usr/share/fonts/truetype/liberation/LiberationSerif-Italic.ttf"),
    ("SerifReg", "/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf"),
    ("SansBold", "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"),
    ("SansReg",  "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf"),
]:
    pdfmetrics.registerFont(TTFont(face, ttf))

OUT = "/home/zory/confrariabrasil-site/Portal-Confraria-Brasil-QRs.pdf"
LOGO = "/home/zory/confraria-qr/logo-confraria-cropped.png"
QR_DIR = "/home/zory/confrariabrasil-site/qr"

PAGE_W, PAGE_H = A4

c = canvas.Canvas(OUT, pagesize=A4)
c.setTitle("Portal Confraria Brasil — Kit de QR Codes")
c.setAuthor("CloudZory")
c.setSubject("QR Codes rastreáveis · eventos + redes sociais")

def fill_bg():
    c.setFillColor(CREAM)
    c.rect(0, 0, PAGE_W, PAGE_H, stroke=0, fill=1)

def footer_decor(page_num):
    """Line + small mountain + page number — Velos signature."""
    y = 1.4 * cm
    c.setStrokeColor(NAVY); c.setLineWidth(0.6)
    c.line(2 * cm, y, PAGE_W - 3 * cm, y)
    # Small mountain on the right
    p = c.beginPath()
    mx = PAGE_W - 2.7 * cm; my = y
    p.moveTo(mx - 14, my)
    p.lineTo(mx - 4,  my - 10)
    p.lineTo(mx + 2,  my - 4)
    p.lineTo(mx + 10, my - 14)
    p.lineTo(mx + 20, my)
    p.close()
    c.setFillColor(NAVY); c.drawPath(p, stroke=0, fill=1)
    # Page number
    c.setFont("SansReg", 7); c.setFillColor(SOFT)
    c.drawString(2 * cm, y - 12, f"{page_num:02d}   Portal Confraria Brasil  ·  Kit de QR Codes")

def header(title, sub=None):
    c.setFont("SerifBold", 22); c.setFillColor(NAVY)
    c.drawString(2 * cm, PAGE_H - 2.6 * cm, title)
    if sub:
        c.setFont("SerifItalic", 11); c.setFillColor(GOLD)
        c.drawString(2 * cm, PAGE_H - 3.2 * cm, sub)
    c.setStrokeColor(NAVY); c.setLineWidth(0.4)
    c.line(2 * cm, PAGE_H - 3.7 * cm, PAGE_W - 2 * cm, PAGE_H - 3.7 * cm)

def qr_card(x, y, w, h, label, sublabel, qr_path, click_url):
    """Render a QR card with label, QR, and a clearly differentiated clickable link pill."""
    # Card background
    c.setFillColor(white)
    c.setStrokeColor(LINE); c.setLineWidth(0.6)
    c.roundRect(x, y, w, h, 8, stroke=1, fill=1)

    # Label (event/social name)
    c.setFont("SerifBold", 14); c.setFillColor(NAVY)
    c.drawString(x + 10 * mm, y + h - 10 * mm, label)
    c.setFont("SerifItalic", 9); c.setFillColor(GOLD)
    c.drawString(x + 10 * mm, y + h - 15 * mm, sublabel)

    # QR image — reserved area at bottom for the click pill
    pill_zone_h = 16 * mm
    qr_size = min(w - 20 * mm, h - 24 * mm - pill_zone_h)
    qx = x + (w - qr_size) / 2
    qy = y + pill_zone_h + 4 * mm
    c.drawImage(qr_path, qx, qy, width=qr_size, height=qr_size, mask='auto')
    c.linkURL(click_url, (qx, qy, qx + qr_size, qy + qr_size), relative=0, thickness=0)

    # Visual separator between QR and link pill
    sep_y = y + pill_zone_h + 2 * mm
    c.setStrokeColor(LINE); c.setLineWidth(0.4); c.setDash(1, 2)
    c.line(x + 8 * mm, sep_y, x + w - 8 * mm, sep_y)
    c.setDash()  # reset

    # Tiny "ou" hint
    c.setFont("SerifItalic", 7); c.setFillColor(SOFT)
    c.drawCentredString(x + w / 2, sep_y - 7, "ou toque no link")

    # Pill-style clickable link (navy bg, gold text — clearly distinct from white QR)
    # Show full short URL, auto-shrink font to fit card width with safe margin
    short = click_url.replace("https://", "")
    pill_h = 7.5 * mm
    pill_pad_x = 5 * mm
    max_text_w = w - 8 * mm - pill_pad_x * 2
    font_size = 9.0
    while c.stringWidth(short, "SansBold", font_size) > max_text_w and font_size > 5.5:
        font_size -= 0.25
    c.setFont("SansBold", font_size)
    pill_w = c.stringWidth(short, "SansBold", font_size) + pill_pad_x * 2
    pill_w = min(pill_w, w - 6 * mm)
    px = x + (w - pill_w) / 2
    py = y + 3 * mm
    c.setFillColor(NAVY); c.setStrokeColor(GOLD); c.setLineWidth(0.7)
    c.roundRect(px, py, pill_w, pill_h, pill_h / 2, stroke=1, fill=1)
    c.setFillColor(GOLD_LIGHT)
    # Vertically center within pill (font baseline tweak)
    text_y = py + (pill_h - font_size * 0.72) / 2
    c.drawCentredString(x + w / 2, text_y, short)
    c.linkURL(click_url, (px, py, px + pill_w, py + pill_h), relative=0, thickness=0)


# ============================================================
# PAGE 1 — Cover
# ============================================================
fill_bg()
# Logo big
c.drawImage(LOGO, 2 * cm, PAGE_H - 9 * cm, width=10 * cm, height=2.4 * cm, mask='auto', preserveAspectRatio=True)

# Big title
c.setFont("SerifBold", 36); c.setFillColor(NAVY)
c.drawString(2 * cm, PAGE_H - 13 * cm, "Kit de QR Codes")
c.setFont("SerifItalic", 22); c.setFillColor(GOLD)
c.drawString(2 * cm, PAGE_H - 14.5 * cm, "rastreáveis · eventos + redes sociais")

# Subtitle / description block
c.setFont("SansReg", 11); c.setFillColor(NAVY)
desc = [
    "Cada QR Code direciona o lead diretamente para o WhatsApp do time comercial",
    "com mensagem pré-preenchida que identifica a origem da conversa.",
    "",
    "Toda interação é rastreada em tempo real no dashboard interno.",
    "Os QRs continuam funcionando em qualquer reprodução (slide, panfleto, projeção).",
]
ty = PAGE_H - 17 * cm
for line in desc:
    c.drawString(2 * cm, ty, line); ty -= 14

# Dashboard CTA
dash_url = "https://confrariabrasil.cloudzory.com/stats/"
c.setFillColor(NAVY)
c.roundRect(2 * cm, 5 * cm, 12 * cm, 1.6 * cm, 8, stroke=0, fill=1)
c.setFont("SerifBold", 13); c.setFillColor(CREAM)
c.drawString(2.6 * cm, 5.8 * cm, "Acompanhar cliques ao vivo →")
c.setFont("SansReg", 9); c.setFillColor(GOLD_LIGHT)
c.drawString(2.6 * cm, 5.3 * cm, dash_url)
c.linkURL(dash_url, (2 * cm, 5 * cm, 14 * cm, 6.6 * cm), relative=0, thickness=0)

# Footer info
c.setFont("SansReg", 8); c.setFillColor(SOFT)
c.drawString(2 * cm, 3.2 * cm, "Atendimento comercial:  (21) 99917-1510")
c.drawString(2 * cm, 2.5 * cm, "Documento gerado por CloudZory · Maio de 2026")

footer_decor(1)
c.showPage()

# ============================================================
# PAGE 2 — Redes Sociais (3 QRs)
# ============================================================
fill_bg()
header("Redes Sociais", "três origens distintas para identificar o canal de captação")

socials = [
    ("Instagram", "Vim do Instagram", f"{QR_DIR}/qr-instagram.png",
     "https://confrariabrasil.cloudzory.com/instagram"),
    ("TikTok",    "Vim do TikTok",    f"{QR_DIR}/qr-tiktok.png",
     "https://confrariabrasil.cloudzory.com/tiktok"),
    ("LinkedIn",  "Vim do LinkedIn",  f"{QR_DIR}/qr-linkedin.png",
     "https://confrariabrasil.cloudzory.com/linkedin"),
]

# Three cards in a row
card_w = 5.4 * cm; card_h = 8 * cm
gap = 0.4 * cm
total_w = card_w * 3 + gap * 2
x0 = (PAGE_W - total_w) / 2
y0 = PAGE_H - 14 * cm
for i, (label, sub, qr, url) in enumerate(socials):
    qr_card(x0 + i * (card_w + gap), y0, card_w, card_h, label, sub, qr, url)

# Explanation
c.setFont("SerifBold", 12); c.setFillColor(NAVY)
c.drawString(2 * cm, y0 - 1.5 * cm, "Mensagem pré-preenchida no WhatsApp:")
c.setFont("SerifItalic", 11); c.setFillColor(GOLD)
c.drawString(2 * cm, y0 - 2.2 * cm,
             "“Vim do {Instagram | TikTok | LinkedIn} e gostaria de entender")
c.drawString(2 * cm, y0 - 2.8 * cm,
             "como posso participar do Portal Confraria Brasil.”")

c.setFont("SansReg", 9); c.setFillColor(SOFT)
notas = [
    "·  O nome da rede social muda automaticamente conforme o QR escaneado.",
    "·  O lead chega no WhatsApp do comercial (21) 99917-1510 já taggueado.",
    "·  Cada scan é registrado no dashboard antes do redirect para o WhatsApp.",
    "·  QRs funcionam em qualquer reprodução: post, story, slide, impresso.",
]
ny = y0 - 4 * cm
for n in notas:
    c.drawString(2 * cm, ny, n); ny -= 12

footer_decor(2)
c.showPage()

# ============================================================
# PAGE 3 — Eventos (4 QRs)
# ============================================================
fill_bg()
header("Eventos", "QRs já em uso · migrados para o novo subdomínio")

events = [
    ("Experiência On-line",  "Vim do evento Experiência On-line",
     f"{QR_DIR}/qr-experiencia-online.png",
     "https://confrariabrasil.cloudzory.com/experiencia-online"),
    ("Experiência Platinium","Vim do evento Experiência Platinium",
     f"{QR_DIR}/qr-experiencia-platinum.png",
     "https://confrariabrasil.cloudzory.com/experiencia-platinum"),
    ("Experiência Black",    "Vim do evento Experiência Black",
     f"{QR_DIR}/qr-experiencia-black.png",
     "https://confrariabrasil.cloudzory.com/experiencia-black"),
    ("Workshop On-line",     "Vim do evento Workshop On-line",
     f"{QR_DIR}/qr-workshop-online.png",
     "https://confrariabrasil.cloudzory.com/workshop-online"),
]

# 2x2 grid
card_w = 7.8 * cm; card_h = 8.5 * cm
gap_x = 0.6 * cm; gap_y = 0.8 * cm
grid_w = card_w * 2 + gap_x
x0 = (PAGE_W - grid_w) / 2
y0 = PAGE_H - 13 * cm

positions = [
    (0, 0), (1, 0), (0, 1), (1, 1)
]
for (col, row), (label, sub, qr, url) in zip(positions, events):
    qx = x0 + col * (card_w + gap_x)
    qy = y0 - row * (card_h + gap_y)
    qr_card(qx, qy, card_w, card_h, label, sub, qr, url)

footer_decor(3)
c.showPage()

# ============================================================
# PAGE 4 — Dashboard & Tracking
# ============================================================
fill_bg()
header("Tracking ao vivo", "métricas em tempo real · atualiza a cada 60 segundos")

# Big CTA button
c.setFillColor(NAVY)
btn_x, btn_y, btn_w, btn_h = 2 * cm, PAGE_H - 8 * cm, PAGE_W - 4 * cm, 3 * cm
c.roundRect(btn_x, btn_y, btn_w, btn_h, 10, stroke=0, fill=1)
c.setFont("SerifBold", 24); c.setFillColor(CREAM)
c.drawCentredString(PAGE_W / 2, btn_y + btn_h - 1.2 * cm, "Abrir Dashboard")
c.setFont("SansReg", 11); c.setFillColor(GOLD_LIGHT)
c.drawCentredString(PAGE_W / 2, btn_y + btn_h - 1.9 * cm,
                    "confrariabrasil.cloudzory.com/stats/")
c.setFont("SerifItalic", 9); c.setFillColor(GOLD_LIGHT)
c.drawCentredString(PAGE_W / 2, btn_y + 0.5 * cm,
                    "→ toque para acessar")
c.linkURL("https://confrariabrasil.cloudzory.com/stats/",
          (btn_x, btn_y, btn_x + btn_w, btn_y + btn_h), relative=0, thickness=0)

# Metrics overview
c.setFont("SerifBold", 14); c.setFillColor(NAVY)
c.drawString(2 * cm, PAGE_H - 10 * cm, "O que o dashboard mostra:")

c.setFont("SansReg", 10); c.setFillColor(NAVY)
items = [
    ("KPIs principais",      "cliques totais · compartilhamentos no WhatsApp · primeiro e último clique"),
    ("Timeline 24h",         "gráfico de cliques por hora nas últimas 24 horas"),
    ("Por evento",           "Experiência On-line · Platinium · Black · Workshop On-line"),
    ("Por rede social",      "Instagram · TikTok · LinkedIn"),
    ("Dispositivo",          "mobile vs desktop · identifica origem real do lead"),
    ("País & IP único",      "geolocalização agregada e detecção de tráfego repetido"),
    ("Últimos 30 cliques",   "lista detalhada para auditoria e cruzamento com mensagens recebidas"),
]
iy = PAGE_H - 11 * cm
for title, desc in items:
    c.setFont("SerifBold", 10); c.setFillColor(GOLD)
    c.drawString(2.4 * cm, iy, title)
    c.setFont("SansReg", 9); c.setFillColor(NAVY)
    c.drawString(2.4 * cm, iy - 11, desc)
    iy -= 26

# How it works box
box_y = 3 * cm
c.setStrokeColor(GOLD); c.setLineWidth(1)
c.setFillColor(white)
c.roundRect(2 * cm, box_y, PAGE_W - 4 * cm, 3 * cm, 8, stroke=1, fill=1)
c.setFont("SerifBold", 11); c.setFillColor(NAVY)
c.drawString(2.4 * cm, box_y + 2.2 * cm, "Como funciona o fluxo")
c.setFont("SansReg", 9); c.setFillColor(NAVY)
flow = "Scan do QR → confrariabrasil.cloudzory.com/{origem} → [registra clique] → WhatsApp com mensagem pré-preenchida → lead chega taggueado no time comercial."
# Wrap manually
words = flow.split(); line = ""; ly = box_y + 1.4 * cm
for w in words:
    test = (line + " " + w).strip()
    if c.stringWidth(test, "SansReg", 9) > PAGE_W - 5 * cm:
        c.drawString(2.4 * cm, ly, line); ly -= 11; line = w
    else:
        line = test
if line: c.drawString(2.4 * cm, ly, line)

footer_decor(4)
c.showPage()

c.save()

# Set readable permissions
os.chmod(OUT, 0o644)
print(f"[OK] PDF gerado: {OUT}")
print(f"     Tamanho: {os.path.getsize(OUT) / 1024:.1f} KB")
