#!/usr/bin/env python3
"""
PDF Template — Bencivenga Method Skill
Generates professional light-theme PDF playbooks for any Bencivenga output.

USAGE: Adapt this template for each delivery. Key variables to change:
- OUTPUT_PATH: where to save
- TITLE / SUBTITLE / AUTHOR: cover page text
- CONTENT_SECTIONS: the actual copy/analysis content
- GROUP_CONFIG: group names, colors, and descriptions

DESIGN SYSTEM:
- Light theme (white bg, dark text)
- Primary accent: Purple #8B5CF6
- Group colors: Purple (proof), Red (pain), Green (if-then), Blue (credo), Orange (myth), Teal (offer)
- Font: Helvetica family (built into ReportLab)
- Cards with colored top border per group
- CTA buttons with group accent color
- Tables with purple header row, alternating row shading
"""

from reportlab.lib.pagesizes import A4
from reportlab.lib.units import mm
from reportlab.lib.colors import HexColor, white
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    PageBreak, KeepTogether, HRFlowable
)
import os

# ═══════════════════════════════════════════
# DESIGN TOKENS (do not change)
# ═══════════════════════════════════════════
PURPLE = HexColor("#8B5CF6")
PURPLE_DARK = HexColor("#7C3AED")
PURPLE_LIGHT = HexColor("#EDE9FE")
GRAY_50 = HexColor("#F9FAFB")
GRAY_100 = HexColor("#F3F4F6")
GRAY_200 = HexColor("#E5E7EB")
GRAY_300 = HexColor("#D1D5DB")
GRAY_500 = HexColor("#6B7280")
GRAY_600 = HexColor("#4B5563")
GRAY_700 = HexColor("#374151")
GRAY_800 = HexColor("#1F2937")
GRAY_900 = HexColor("#111827")
GREEN = HexColor("#10B981")
GREEN_LIGHT = HexColor("#D1FAE5")
ORANGE = HexColor("#F59E0B")
ORANGE_LIGHT = HexColor("#FEF3C7")
RED = HexColor("#EF4444")
RED_LIGHT = HexColor("#FEE2E2")
BLUE = HexColor("#3B82F6")
BLUE_LIGHT = HexColor("#DBEAFE")
TEAL = HexColor("#14B8A6")
TEAL_LIGHT = HexColor("#CCFBF1")

# Group color map — reuse across all PDFs
GROUP_COLORS = {
    "PROOF-LED": (PURPLE, PURPLE_LIGHT),
    "PAIN POINT": (RED, RED_LIGHT),
    "IF...THEN": (GREEN, GREEN_LIGHT),
    "CREDO / POSITIONING": (BLUE, BLUE_LIGHT),
    "MYTH-BUSTING": (ORANGE, ORANGE_LIGHT),
    "URGENCY / OFFER": (TEAL, TEAL_LIGHT),
    # Generic fallbacks
    "ANALYSIS": (PURPLE, PURPLE_LIGHT),
    "OPTIMIZATION": (BLUE, BLUE_LIGHT),
    "HEADLINES": (GREEN, GREEN_LIGHT),
    "FASCINATIONS": (ORANGE, ORANGE_LIGHT),
    "PROOF": (RED, RED_LIGHT),
    "OFFER": (TEAL, TEAL_LIGHT),
}


def get_styles():
    """Standard style dictionary for all Bencivenga PDFs."""
    return {
        'cover_title': ParagraphStyle(
            'cover_title', fontName='Helvetica-Bold', fontSize=32, leading=38,
            textColor=GRAY_900, alignment=TA_CENTER, spaceAfter=8),
        'cover_subtitle': ParagraphStyle(
            'cover_subtitle', fontName='Helvetica', fontSize=18, leading=24,
            textColor=PURPLE, alignment=TA_CENTER, spaceAfter=6),
        'cover_author': ParagraphStyle(
            'cover_author', fontName='Helvetica', fontSize=14, leading=18,
            textColor=GRAY_600, alignment=TA_CENTER),
        'cover_badge': ParagraphStyle(
            'cover_badge', fontName='Helvetica-Bold', fontSize=11, leading=14,
            textColor=PURPLE_DARK, alignment=TA_CENTER),
        'section_title': ParagraphStyle(
            'section_title', fontName='Helvetica-Bold', fontSize=22, leading=28,
            textColor=GRAY_900, spaceAfter=12, spaceBefore=4),
        'group_desc': ParagraphStyle(
            'group_desc', fontName='Helvetica-Oblique', fontSize=10, leading=14,
            textColor=GRAY_600, spaceAfter=12),
        'ad_headline': ParagraphStyle(
            'ad_headline', fontName='Helvetica-Bold', fontSize=16, leading=21,
            textColor=GRAY_900, spaceAfter=4),
        'ad_description': ParagraphStyle(
            'ad_description', fontName='Helvetica-Oblique', fontSize=10, leading=14,
            textColor=GRAY_600, spaceAfter=8),
        'ad_body': ParagraphStyle(
            'ad_body', fontName='Helvetica', fontSize=9.5, leading=14,
            textColor=GRAY_800, alignment=TA_LEFT, spaceAfter=6),
        'ad_cta': ParagraphStyle(
            'ad_cta', fontName='Helvetica-Bold', fontSize=10, leading=14,
            textColor=white, alignment=TA_CENTER),
        'body_text': ParagraphStyle(
            'body_text', fontName='Helvetica', fontSize=10, leading=15,
            textColor=GRAY_800, spaceAfter=6),
        'body_bold': ParagraphStyle(
            'body_bold', fontName='Helvetica-Bold', fontSize=10, leading=15,
            textColor=GRAY_900, spaceAfter=4),
        'eq_component': ParagraphStyle(
            'eq_component', fontName='Helvetica-Bold', fontSize=10, leading=14,
            textColor=PURPLE_DARK, spaceAfter=2),
        'eq_detail': ParagraphStyle(
            'eq_detail', fontName='Helvetica', fontSize=9, leading=13,
            textColor=GRAY_700, spaceAfter=8),
        'table_header': ParagraphStyle(
            'table_header', fontName='Helvetica-Bold', fontSize=8, leading=11,
            textColor=white, alignment=TA_CENTER),
        'table_cell': ParagraphStyle(
            'table_cell', fontName='Helvetica', fontSize=8, leading=11,
            textColor=GRAY_800, alignment=TA_LEFT),
        'table_cell_center': ParagraphStyle(
            'table_cell_center', fontName='Helvetica', fontSize=8, leading=11,
            textColor=GRAY_800, alignment=TA_CENTER),
        'footer': ParagraphStyle(
            'footer', fontName='Helvetica', fontSize=7, leading=9,
            textColor=GRAY_500, alignment=TA_CENTER),
        'score_big': ParagraphStyle(
            'score_big', fontName='Helvetica-Bold', fontSize=36, leading=42,
            textColor=PURPLE, alignment=TA_CENTER),
        'verdict': ParagraphStyle(
            'verdict', fontName='Helvetica-Bold', fontSize=14, leading=18,
            textColor=GRAY_900, alignment=TA_CENTER),
    }


def build_cover(story, styles, title, subtitle, author, badge_text, page_width):
    """Build a standard cover page."""
    story.append(Spacer(1, 50*mm))
    story.append(HRFlowable(width="100%", thickness=3, color=PURPLE, spaceAfter=15))
    for line in title.split("\n"):
        story.append(Paragraph(line, styles['cover_title']))
    story.append(Spacer(1, 8*mm))
    story.append(Paragraph(subtitle, styles['cover_subtitle']))
    story.append(Spacer(1, 5*mm))
    story.append(HRFlowable(width="40%", thickness=1, color=GRAY_300, spaceAfter=10))
    story.append(Paragraph(f"por {author}", styles['cover_author']))
    story.append(Spacer(1, 15*mm))
    if badge_text:
        badge = Table(
            [[Paragraph(badge_text, styles['cover_badge'])]],
            colWidths=[page_width * 0.8]
        )
        badge.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, -1), PURPLE_LIGHT),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('TOPPADDING', (0, 0), (-1, -1), 10),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 10),
            ('LEFTPADDING', (0, 0), (-1, -1), 15),
            ('RIGHTPADDING', (0, 0), (-1, -1), 15),
        ]))
        story.append(badge)
    story.append(Spacer(1, 30*mm))
    story.append(HRFlowable(width="100%", thickness=1, color=GRAY_200, spaceAfter=8))
    story.append(Paragraph(
        "Baseado nos frameworks de Gary Bencivenga \u2022 80%+ win rate \u2022 $1B+ em vendas rastreadas",
        styles['footer']
    ))
    story.append(PageBreak())


def build_equation_page(story, styles, eq_items, tq_items, page_width):
    """Build the Persuasion Equation + Three Questions page."""
    story.append(Paragraph("Fundacao Estrategica", styles['section_title']))
    story.append(HRFlowable(width="100%", thickness=2, color=PURPLE, spaceAfter=15))

    # Persuasion Equation
    eq_header = Table(
        [[Paragraph('<font color="#8B5CF6"><b>EQUACAO DA PERSUASAO (Bencivenga)</b></font>', styles['body_bold'])]],
        colWidths=[page_width]
    )
    eq_header.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), PURPLE_LIGHT),
        ('TOPPADDING', (0, 0), (-1, -1), 10),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 10),
        ('LEFTPADDING', (0, 0), (-1, -1), 15),
    ]))
    story.append(eq_header)
    story.append(Spacer(1, 3*mm))
    for title, detail in eq_items:
        story.append(Paragraph(f"\u25b6 {title}", styles['eq_component']))
        story.append(Paragraph(detail, styles['eq_detail']))
    story.append(Spacer(1, 5*mm))

    # Three Questions
    tq_header = Table(
        [[Paragraph('<font color="#8B5CF6"><b>TESTE DAS 3 PERGUNTAS</b></font>', styles['body_bold'])]],
        colWidths=[page_width]
    )
    tq_header.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), PURPLE_LIGHT),
        ('TOPPADDING', (0, 0), (-1, -1), 10),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 10),
        ('LEFTPADDING', (0, 0), (-1, -1), 15),
    ]))
    story.append(tq_header)
    story.append(Spacer(1, 3*mm))
    for title, detail in tq_items:
        story.append(Paragraph(f"\u25b6 {title}", styles['eq_component']))
        story.append(Paragraph(detail, styles['eq_detail']))
    story.append(PageBreak())


def build_group_header(story, styles, group_name, subtitle, quote, accent, page_width):
    """Build a colored group header bar."""
    gh = Table(
        [[Paragraph(f'<font color="white"><b>GRUPO: {group_name}</b></font>',
                     ParagraphStyle('gh', fontName='Helvetica-Bold', fontSize=14, leading=18, textColor=white))]],
        colWidths=[page_width]
    )
    gh.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), accent),
        ('TOPPADDING', (0, 0), (-1, -1), 10),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 10),
        ('LEFTPADDING', (0, 0), (-1, -1), 15),
    ]))
    story.append(gh)
    story.append(Spacer(1, 2*mm))
    story.append(Paragraph(f"{subtitle} \u2014 <i>{quote}</i>", styles['group_desc']))
    story.append(Spacer(1, 4*mm))


def build_ad_card(ad, accent, styles, page_width):
    """Build a single ad card. ad dict keys: num, formula, headline, description, body, cta"""
    elements = []

    # Header row: number + formula
    header = Table(
        [[
            Paragraph(f'<b>ANUNCIO {ad["num"]}</b>',
                      ParagraphStyle('an', fontName='Helvetica-Bold', fontSize=9, leading=12, textColor=accent)),
            Paragraph(ad["formula"],
                      ParagraphStyle('ft', fontName='Helvetica', fontSize=7.5, leading=10, textColor=accent, alignment=TA_RIGHT)),
        ]],
        colWidths=[page_width * 0.3, page_width * 0.7 - 20]
    )
    header.setStyle(TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('TOPPADDING', (0, 0), (-1, -1), 0),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
        ('LEFTPADDING', (0, 0), (0, 0), 0),
        ('RIGHTPADDING', (-1, -1), (-1, -1), 0),
    ]))
    elements.append(header)
    elements.append(Spacer(1, 2*mm))
    elements.append(Paragraph(ad["headline"], styles['ad_headline']))
    elements.append(Paragraph(ad["description"], styles['ad_description']))

    for p in ad["body"].strip().split("\n\n"):
        elements.append(Paragraph(p.replace("\n", "<br/>"), styles['ad_body']))

    elements.append(Spacer(1, 2*mm))

    # CTA button
    cta = Table(
        [[Paragraph(f'<b>{ad["cta"]}</b>', styles['ad_cta'])]],
        colWidths=[page_width * 0.45]
    )
    cta.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), accent),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('TOPPADDING', (0, 0), (-1, -1), 7),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 7),
    ]))
    elements.append(cta)

    # Wrap in card
    card = Table([[e] for e in elements], colWidths=[page_width - 20])
    card.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), white),
        ('TOPPADDING', (0, 0), (-1, -1), 2),
        ('BOTTOMPADDING', (0, -1), (-1, -1), 8),
        ('LEFTPADDING', (0, 0), (-1, -1), 12),
        ('RIGHTPADDING', (0, 0), (-1, -1), 12),
        ('LINEABOVE', (0, 0), (-1, 0), 3, accent),
        ('LINEBEFORE', (0, 0), (0, -1), 0.5, GRAY_200),
        ('LINEAFTER', (-1, 0), (-1, -1), 0.5, GRAY_200),
        ('LINEBELOW', (0, -1), (-1, -1), 0.5, GRAY_200),
    ]))
    return KeepTogether([card])


def build_summary_table(story, styles, rows, page_width):
    """Build summary table. rows = list of [num, group, headline, formula]"""
    col_widths = [22, 55, page_width - 22 - 55 - 95, 95]
    header = [
        Paragraph("#", styles['table_header']),
        Paragraph("Grupo", styles['table_header']),
        Paragraph("Headline", styles['table_header']),
        Paragraph("Formula Bencivenga", styles['table_header']),
    ]
    data = [header]
    for r in rows:
        data.append([
            Paragraph(r[0], styles['table_cell_center']),
            Paragraph(r[1], styles['table_cell']),
            Paragraph(f"<b>{r[2]}</b>", styles['table_cell']),
            Paragraph(r[3], styles['table_cell']),
        ])
    t = Table(data, colWidths=col_widths, repeatRows=1)
    t_style = [
        ('BACKGROUND', (0, 0), (-1, 0), PURPLE),
        ('GRID', (0, 0), (-1, -1), 0.5, GRAY_200),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('TOPPADDING', (0, 0), (-1, -1), 5),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 5),
        ('LEFTPADDING', (0, 0), (-1, -1), 6),
        ('RIGHTPADDING', (0, 0), (-1, -1), 6),
    ]
    for i in range(1, len(data)):
        if i % 2 == 0:
            t_style.append(('BACKGROUND', (0, i), (-1, i), GRAY_50))
    t.setStyle(TableStyle(t_style))
    story.append(t)


def build_score_card(story, styles, score, verdict, breakdown, page_width):
    """Build a Bencivenga Score card for ANALYZE mode."""
    # Big score
    score_box = Table(
        [[Paragraph(f"{score}/100", styles['score_big'])]],
        colWidths=[page_width * 0.4]
    )
    score_box.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), PURPLE_LIGHT),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('TOPPADDING', (0, 0), (-1, -1), 15),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 15),
    ]))
    story.append(score_box)
    story.append(Spacer(1, 3*mm))
    story.append(Paragraph(verdict, styles['verdict']))
    story.append(Spacer(1, 5*mm))

    # Breakdown table
    header = [
        Paragraph("#", styles['table_header']),
        Paragraph("Dimensao", styles['table_header']),
        Paragraph("Nota", styles['table_header']),
        Paragraph("Avaliacao", styles['table_header']),
    ]
    data = [header]
    for item in breakdown:
        data.append([
            Paragraph(str(item[0]), styles['table_cell_center']),
            Paragraph(f"<b>{item[1]}</b>", styles['table_cell']),
            Paragraph(f"<b>{item[2]}/10</b>", styles['table_cell_center']),
            Paragraph(item[3], styles['table_cell']),
        ])
    col_widths = [22, page_width * 0.3, 35, page_width - 22 - page_width * 0.3 - 35]
    t = Table(data, colWidths=col_widths, repeatRows=1)
    t.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), PURPLE),
        ('GRID', (0, 0), (-1, -1), 0.5, GRAY_200),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('TOPPADDING', (0, 0), (-1, -1), 5),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 5),
        ('LEFTPADDING', (0, 0), (-1, -1), 6),
        ('RIGHTPADDING', (0, 0), (-1, -1), 6),
    ]))
    story.append(t)


def build_ab_test_plan(story, styles, tests, page_width):
    """Build A/B test plan section. tests = list of (title, matchup, rationale)"""
    story.append(Paragraph("Plano de Testes A/B", styles['section_title']))
    story.append(HRFlowable(width="100%", thickness=2, color=PURPLE, spaceAfter=12))
    for title, matchup, rationale in tests:
        card = Table(
            [
                [Paragraph(f'<font color="#8B5CF6"><b>{title}</b></font>', styles['body_bold'])],
                [Paragraph(f'<b>{matchup}</b>', styles['body_text'])],
                [Paragraph(f'<i>{rationale}</i>',
                           ParagraphStyle('tr', fontName='Helvetica-Oblique', fontSize=9, leading=13, textColor=GRAY_600))],
            ],
            colWidths=[page_width - 10]
        )
        card.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, -1), GRAY_50),
            ('TOPPADDING', (0, 0), (-1, 0), 10),
            ('BOTTOMPADDING', (0, -1), (-1, -1), 10),
            ('LEFTPADDING', (0, 0), (-1, -1), 15),
            ('RIGHTPADDING', (0, 0), (-1, -1), 15),
            ('LINEABOVE', (0, 0), (-1, 0), 3, PURPLE),
        ]))
        story.append(card)
        story.append(Spacer(1, 5*mm))


def create_pdf(output_path, page_width=None):
    """Create document and return (doc, story, styles, page_width)."""
    doc = SimpleDocTemplate(
        output_path, pagesize=A4,
        leftMargin=20*mm, rightMargin=20*mm,
        topMargin=18*mm, bottomMargin=18*mm
    )
    styles = get_styles()
    pw = A4[0] - 40*mm
    return doc, [], styles, pw
