"""services/report_pdf.py — Premium PDF report generator using ReportLab."""
from __future__ import annotations
import io
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import mm
from reportlab.platypus import (
    HRFlowable, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle, KeepTogether,
)
from reportlab.pdfgen import canvas as rl_canvas
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT

# ── Colour palette ────────────────────────────────────────────────
RED       = colors.HexColor("#C8102E")
RED_DARK  = colors.HexColor("#9E0B22")
RED_DEEP  = colors.HexColor("#6B0000")
RED_LIGHT = colors.HexColor("#FEE8EC")
RED_MID   = colors.HexColor("#FDD0D8")
RED_PALE  = colors.HexColor("#FCF0F2")
NAVY      = colors.HexColor("#5C0915")
GREY      = colors.HexColor("#6B2233")
LIGHT_GREY= colors.HexColor("#9E6370")
GREEN     = colors.HexColor("#0E7C3A")
GREEN_LT  = colors.HexColor("#E8F7EE")
GOLD      = colors.HexColor("#F5A623")
GOLD_LT   = colors.HexColor("#FEF3DC")
WHITE     = colors.white
BD        = colors.HexColor("#EDD8DC")


# ── Canvas with header / footer / watermark ───────────────────────
class BrandedCanvas(rl_canvas.Canvas):
    def __init__(self, *args, report_title="Session Report", **kwargs):
        super().__init__(*args, **kwargs)
        self._report_title = report_title
        self._page_num = 0

    def showPage(self):
        self._page_num += 1
        self._draw_page_chrome()
        super().showPage()

    def save(self):
        self._page_num += 1
        self._draw_page_chrome()
        super().save()

    def _draw_page_chrome(self):
        W, H = A4

        # ── Diagonal watermark — light grey, single line ──────────
        self.saveState()
        self.setFont("Helvetica-Bold", 48)
        self.setFillGray(0.82)   # light grey, no overlap with content
        self.translate(W / 2, H / 2)
        self.rotate(35)
        self.drawCentredString(0, 0, "GOLS EdTech")
        self.restoreState()

        # ── Header bar ────────────────────────────────────────────
        self.saveState()
        self.setFillColor(RED_DEEP)
        self.rect(0, H - 18*mm, W, 18*mm, fill=1, stroke=0)
        self.setFillColor(RED)
        self.rect(W * 0.35, H - 18*mm, W * 0.65, 18*mm, fill=1, stroke=0)

        # 🎭 icon + brand name left
        self.setFont("Helvetica-Bold", 13)
        self.setFillColor(WHITE)
        self.drawString(18*mm, H - 10.5*mm, "RolePilot")
        self.setFont("Helvetica", 7.5)
        self.setFillColor(colors.HexColor("#FFCCD5"))
        self.drawString(18*mm, H - 15.5*mm, "AI Roleplay Training  |  GOLS EdTech")

        # Roleplay icon circle (simple circle with text as decoration)
        self.setFillColor(colors.HexColor("#FFFFFF"))
        self.setFillAlpha(0.15)
        self.circle(13*mm, H - 9*mm, 4.5*mm, fill=1, stroke=0)
        self.setFillAlpha(1)
        self.setFont("Helvetica-Bold", 9)
        self.setFillColor(WHITE)
        self.drawCentredString(13*mm, H - 10.2*mm, "RP")

        # Report title — centre zone only, max width so it never hits brand or page-num
        # Left brand occupies ~58mm, right page-num ~28mm → centre zone ~A4_w - 86mm
        BRAND_END  = 62*mm
        PGNUM_START= W - 28*mm
        centre_zone_w = PGNUM_START - BRAND_END   # available px for title
        self.setFont("Helvetica-Bold", 8.5)
        self.setFillColor(WHITE)
        title_full = self._report_title
        # Measure and trim until it fits
        while self.stringWidth(title_full, "Helvetica-Bold", 8.5) > centre_zone_w and len(title_full) > 8:
            title_full = title_full[:-1]
        if title_full != self._report_title:
            title_full = title_full.rstrip() + "…"
        title_x = BRAND_END + centre_zone_w / 2
        self.drawCentredString(title_x, H - 11*mm, title_full)

        # Page number right
        self.setFont("Helvetica", 8)
        self.setFillColor(colors.HexColor("#FFCCD5"))
        self.drawRightString(W - 18*mm, H - 11*mm, f"Page {self._page_num}")
        self.drawRightString(W - 18*mm, H - 15.5*mm, "Confidential")
        self.restoreState()

        # ── Footer bar ────────────────────────────────────────────
        self.saveState()
        self.setFillColor(RED_PALE)
        self.rect(0, 0, W, 13*mm, fill=1, stroke=0)
        # top border line
        self.setStrokeColor(BD)
        self.setLineWidth(0.5)
        self.line(18*mm, 13*mm, W - 18*mm, 13*mm)

        self.setFont("Helvetica", 7.5)
        self.setFillColor(LIGHT_GREY)
        self.drawString(18*mm, 5*mm, "Generated by RolePilot AI Agent  ·  GOLS EdTech  ·  golsedtech.com")
        self.setFont("Helvetica-Bold", 7.5)
        self.setFillColor(RED)
        self.drawRightString(W - 18*mm, 5*mm, "Powered by OpenAI GPT-4o")
        self.restoreState()

        # ── Thin red accent line under header ─────────────────────
        self.saveState()
        self.setStrokeColor(RED_MID)
        self.setLineWidth(1)
        self.line(0, H - 18*mm, W, H - 18*mm)
        self.restoreState()


def _pill(text: str, bg: str, fg: str) -> Table:
    """Small pill badge as a 1-cell table."""
    p = Paragraph(f'<b>{text}</b>', ParagraphStyle(
        "pill", fontName="Helvetica-Bold", fontSize=7.5,
        textColor=colors.HexColor(fg), alignment=TA_CENTER,
    ))
    t = Table([[p]], colWidths=[28*mm])
    t.setStyle(TableStyle([
        ("BACKGROUND",   (0,0),(-1,-1), colors.HexColor(bg)),
        ("TOPPADDING",   (0,0),(-1,-1), 3),
        ("BOTTOMPADDING",(0,0),(-1,-1), 3),
        ("LEFTPADDING",  (0,0),(-1,-1), 6),
        ("RIGHTPADDING", (0,0),(-1,-1), 6),
        ("ROUNDEDCORNERS", (0,0),(-1,-1), [4,4,4,4]),
    ]))
    return t


def generate_pdf(report) -> bytes:
    buf = io.BytesIO()

    doc = SimpleDocTemplate(
        buf, pagesize=A4,
        topMargin=22*mm,      # below header bar
        bottomMargin=17*mm,   # above footer bar
        leftMargin=18*mm,
        rightMargin=18*mm,
    )

    W = A4[0] - 36*mm   # usable width

    # ── Style helpers ─────────────────────────────────────────────
    def H1(txt):
        return Paragraph(txt, ParagraphStyle(
            "H1", fontName="Helvetica-Bold", fontSize=17,
            textColor=NAVY, spaceAfter=2, spaceBefore=0,
        ))

    def H2(txt):
        return Paragraph(txt, ParagraphStyle(
            "H2", fontName="Helvetica-Bold", fontSize=10,
            textColor=WHITE, spaceAfter=0, spaceBefore=8,
        ))

    def body(txt, bold=False, color=GREY):
        return Paragraph(txt, ParagraphStyle(
            "body", fontName="Helvetica-Bold" if bold else "Helvetica",
            fontSize=8.5, textColor=color, leading=13,
        ))

    def section_header(title: str) -> Table:
        """Red banner row used as a section title."""
        p = Paragraph(f'<b>{title}</b>', ParagraphStyle(
            "sh", fontName="Helvetica-Bold", fontSize=9.5,
            textColor=WHITE, spaceBefore=0, spaceAfter=0,
        ))
        t = Table([[p]], colWidths=[W])
        t.setStyle(TableStyle([
            ("BACKGROUND",    (0,0),(-1,-1), RED_DARK),
            ("TOPPADDING",    (0,0),(-1,-1), 5),
            ("BOTTOMPADDING", (0,0),(-1,-1), 5),
            ("LEFTPADDING",   (0,0),(-1,-1), 8),
        ]))
        return t

    story = []

    # ════════════════════════════════════════════════════════════════
    # TITLE BLOCK
    # ════════════════════════════════════════════════════════════════
    story.append(Spacer(1, 3*mm))
    story.append(H1(f"Session Report"))
    story.append(Paragraph(
        report.scenario_title,
        ParagraphStyle("sub", fontName="Helvetica", fontSize=11,
                       textColor=RED, spaceAfter=5),
    ))
    story.append(HRFlowable(width=W, thickness=1.5, color=RED, spaceAfter=6))

    # ════════════════════════════════════════════════════════════════
    # META TABLE  (2-column key/value grid)
    # ════════════════════════════════════════════════════════════════
    def kv(k, v):
        return [
            Paragraph(k, ParagraphStyle("k", fontName="Helvetica-Bold", fontSize=8,
                                        textColor=NAVY)),
            Paragraph(str(v), ParagraphStyle("v", fontName="Helvetica", fontSize=8,
                                             textColor=GREY)),
        ]

    meta_data = [
        kv("Learner Role",  report.learner_role) +
        kv("AI Character",  report.ai_character),

        kv("Difficulty",    report.difficulty) +
        kv("Language",      report.language),

        kv("Mode",          report.mode.title()) +
        kv("Duration",      f"{report.duration_seconds // 60}m {report.duration_seconds % 60}s"),

        kv("Turns",         str(report.turns_completed)) +
        kv("Generated",     report.generated_at[:10]),
    ]

    col = W / 4
    mt = Table(meta_data, colWidths=[col*0.55, col*0.95, col*0.55, col*0.95])
    mt.setStyle(TableStyle([
        ("FONTSIZE",       (0,0),(-1,-1), 8),
        ("VALIGN",         (0,0),(-1,-1), "MIDDLE"),
        ("TOPPADDING",     (0,0),(-1,-1), 4),
        ("BOTTOMPADDING",  (0,0),(-1,-1), 4),
        ("LEFTPADDING",    (0,0),(-1,-1), 6),
        ("RIGHTPADDING",   (0,0),(-1,-1), 6),
        ("ROWBACKGROUNDS", (0,0),(-1,-1), [RED_PALE, WHITE]),
        ("BOX",            (0,0),(-1,-1), 0.5, BD),
        ("INNERGRID",      (0,0),(-1,-1), 0.3, BD),
    ]))
    story.append(mt)
    story.append(Spacer(1, 6*mm))

    # ════════════════════════════════════════════════════════════════
    # SCORE + VERDICT  (side by side)
    # ════════════════════════════════════════════════════════════════
    score_color   = GREEN if report.overall_score >= 7 else GOLD if report.overall_score >= 5 else RED
    score_hex     = "#0E7C3A" if report.overall_score >= 7 else "#F5A623" if report.overall_score >= 5 else "#C8102E"
    verdict_txt   = "PASS" if report.verdict == "pass" else "NEEDS IMPROVEMENT"
    verdict_bg    = "#E8F7EE" if report.verdict == "pass" else "#FEE8EC"
    verdict_fg    = "#0E7C3A" if report.verdict == "pass" else "#C8102E"
    verdict_icon  = "Passed" if report.verdict == "pass" else "Needs Work"

    score_cell = Paragraph(
        f'<font size="36" color="{score_hex}"><b>{report.overall_score:.1f}</b></font>'
        f'<font size="14" color="#9E6370"> /10</font>',
        ParagraphStyle("sc", fontName="Helvetica", fontSize=36, alignment=TA_CENTER),
    )
    verdict_cell = Table([[
        Paragraph(
            f'<font color="{verdict_fg}"><b>{verdict_txt}</b></font>',
            ParagraphStyle("vt", fontName="Helvetica-Bold", fontSize=10,
                           textColor=colors.HexColor(verdict_fg), alignment=TA_CENTER),
        )
    ]], colWidths=[55*mm])
    verdict_cell.setStyle(TableStyle([
        ("BACKGROUND",    (0,0),(-1,-1), colors.HexColor(verdict_bg)),
        ("TOPPADDING",    (0,0),(-1,-1), 10),
        ("BOTTOMPADDING", (0,0),(-1,-1), 10),
        ("BOX",           (0,0),(-1,-1), 0.8, colors.HexColor(verdict_fg)),
    ]))

    score_label = Paragraph("OVERALL SCORE", ParagraphStyle(
        "sl", fontName="Helvetica-Bold", fontSize=7, textColor=LIGHT_GREY,
        alignment=TA_CENTER, spaceBefore=2,
    ))

    score_block = Table(
        [[score_cell, verdict_cell]],
        colWidths=[W * 0.35, W * 0.65],
    )
    score_block.setStyle(TableStyle([
        ("VALIGN",        (0,0),(-1,-1), "MIDDLE"),
        ("ALIGN",         (0,0),(-1,-1), "CENTER"),
        ("BACKGROUND",    (0,0),(0,-1),  RED_PALE),
        ("BOX",           (0,0),(-1,-1), 0.5, BD),
        ("INNERGRID",     (0,0),(-1,-1), 0.3, BD),
        ("TOPPADDING",    (0,0),(-1,-1), 10),
        ("BOTTOMPADDING", (0,0),(-1,-1), 10),
    ]))

    story.append(KeepTogether([section_header("Overall Score"), Spacer(1,1), score_block]))
    story.append(Spacer(1, 5*mm))

    # ════════════════════════════════════════════════════════════════
    # PERFORMANCE DIMENSIONS  (progress-bar style)
    # ════════════════════════════════════════════════════════════════
    dim_rows = [[
        Paragraph("<b>Dimension</b>", ParagraphStyle("dh", fontName="Helvetica-Bold",
                                                      fontSize=8.5, textColor=WHITE)),
        Paragraph("<b>Score</b>",     ParagraphStyle("dh2", fontName="Helvetica-Bold",
                                                      fontSize=8.5, textColor=WHITE,
                                                      alignment=TA_CENTER)),
        Paragraph("<b>Level</b>",     ParagraphStyle("dh3", fontName="Helvetica-Bold",
                                                      fontSize=8.5, textColor=WHITE,
                                                      alignment=TA_CENTER)),
        Paragraph("<b>Progress</b>",  ParagraphStyle("dh4", fontName="Helvetica-Bold",
                                                      fontSize=8.5, textColor=WHITE)),
    ]]

    for d in report.dimensions:
        if d.level == "high":
            lvl_bg, lvl_fg, bar_color = "#E8F7EE", "#0E7C3A", "#0E7C3A"
        elif d.level == "mid":
            lvl_bg, lvl_fg, bar_color = "#FEF3DC", "#B45309", "#F5A623"
        else:
            lvl_bg, lvl_fg, bar_color = "#FEE8EC", "#C8102E", "#C8102E"

        # Bar as nested table
        pct = max(d.score, 2)
        bar_filled = Table([[""]], colWidths=[pct * 0.6 * mm if pct * 0.6 * mm < 60*mm else 60*mm])
        bar_filled.setStyle(TableStyle([
            ("BACKGROUND",    (0,0),(-1,-1), colors.HexColor(bar_color)),
            ("TOPPADDING",    (0,0),(-1,-1), 4),
            ("BOTTOMPADDING", (0,0),(-1,-1), 4),
        ]))
        bar_empty = Table([[""]], colWidths=[max(60*mm - pct * 0.6 * mm, 0.5*mm)])
        bar_empty.setStyle(TableStyle([
            ("BACKGROUND",  (0,0),(-1,-1), BD),
            ("TOPPADDING",  (0,0),(-1,-1), 4),
            ("BOTTOMPADDING",(0,0),(-1,-1), 4),
        ]))

        dim_rows.append([
            Paragraph(d.name, ParagraphStyle("dn", fontName="Helvetica", fontSize=8.5, textColor=GREY)),
            Paragraph(f"<b>{d.score}%</b>", ParagraphStyle("ds", fontName="Helvetica-Bold",
                                                             fontSize=8.5, textColor=colors.HexColor(lvl_fg),
                                                             alignment=TA_CENTER)),
            Paragraph(f"<b>{d.level.title()}</b>", ParagraphStyle("dl", fontName="Helvetica-Bold",
                                                                    fontSize=8, textColor=colors.HexColor(lvl_fg),
                                                                    alignment=TA_CENTER)),
            Table([[bar_filled, bar_empty]], colWidths=[
                min(pct * 0.6 * mm, 60*mm),
                max(60*mm - pct * 0.6 * mm, 0.5*mm),
            ]),
        ])

    dim_col = [W*0.38, W*0.12, W*0.13, W*0.37]
    dt = Table(dim_rows, colWidths=dim_col)
    dt.setStyle(TableStyle([
        ("BACKGROUND",    (0,0),(-1,0),  RED_DARK),
        ("TEXTCOLOR",     (0,0),(-1,0),  WHITE),
        ("FONTNAME",      (0,0),(-1,0),  "Helvetica-Bold"),
        ("FONTSIZE",      (0,0),(-1,-1), 8.5),
        ("ROWBACKGROUNDS",(0,1),(-1,-1), [RED_PALE, WHITE]),
        ("VALIGN",        (0,0),(-1,-1), "MIDDLE"),
        ("ALIGN",         (1,0),(2,-1),  "CENTER"),
        ("BOX",           (0,0),(-1,-1), 0.5, BD),
        ("INNERGRID",     (0,0),(-1,-1), 0.3, BD),
        ("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(KeepTogether([section_header("Performance Dimensions"), Spacer(1,1), dt]))
    story.append(Spacer(1, 5*mm))

    # ════════════════════════════════════════════════════════════════
    # COACHING FEEDBACK  (coloured cards)
    # ════════════════════════════════════════════════════════════════
    fb_rows = [[
        Paragraph("<b>Type</b>", ParagraphStyle("fbh", fontName="Helvetica-Bold",
                                                 fontSize=8.5, textColor=WHITE)),
        Paragraph("<b>Feedback</b>", ParagraphStyle("fbh2", fontName="Helvetica-Bold",
                                                     fontSize=8.5, textColor=WHITE)),
    ]]

    for item in report.feedback:
        if item.type == "strength":
            type_bg, type_fg, icon = "#E8F7EE", "#0E7C3A", "Strength"
        elif item.type == "weakness":
            type_bg, type_fg, icon = "#FEE8EC", "#C8102E", "Weakness"
        else:
            type_bg, type_fg, icon = "#FEF3DC", "#B45309", "Suggestion"

        fb_rows.append([
            Paragraph(f"<b>{icon}</b>", ParagraphStyle("ft", fontName="Helvetica-Bold",
                                                        fontSize=8, textColor=colors.HexColor(type_fg),
                                                        alignment=TA_CENTER)),
            Paragraph(item.text, ParagraphStyle("fb", fontName="Helvetica", fontSize=8.5,
                                                textColor=GREY, leading=12)),
        ])

    fbt = Table(fb_rows, colWidths=[W*0.18, W*0.82])
    fbt.setStyle(TableStyle([
        ("BACKGROUND",    (0,0),(-1,0),  RED_DARK),
        ("TEXTCOLOR",     (0,0),(-1,0),  WHITE),
        ("ROWBACKGROUNDS",(0,1),(-1,-1), [RED_PALE, WHITE]),
        ("VALIGN",        (0,0),(-1,-1), "MIDDLE"),
        ("ALIGN",         (0,1),(0,-1),  "CENTER"),
        ("BOX",           (0,0),(-1,-1), 0.5, BD),
        ("INNERGRID",     (0,0),(-1,-1), 0.3, BD),
        ("TOPPADDING",    (0,0),(-1,-1), 6),
        ("BOTTOMPADDING", (0,0),(-1,-1), 6),
        ("LEFTPADDING",   (0,0),(-1,-1), 6),
        ("RIGHTPADDING",  (0,0),(-1,-1), 6),
    ]))

    story.append(KeepTogether([section_header("Coaching Feedback"), Spacer(1,1), fbt]))
    story.append(Spacer(1, 5*mm))

    # ════════════════════════════════════════════════════════════════
    # CONVERSATION TRANSCRIPT
    # ════════════════════════════════════════════════════════════════
    tr_rows = [[
        Paragraph("<b>Speaker</b>", ParagraphStyle("trh", fontName="Helvetica-Bold",
                                                    fontSize=8.5, textColor=WHITE)),
        Paragraph("<b>Message</b>", ParagraphStyle("trh2", fontName="Helvetica-Bold",
                                                    fontSize=8.5, textColor=WHITE)),
    ]]

    for msg in report.transcript:
        if msg.content in ("[session_start]", "[session_end]"):
            continue
        is_learner = msg.role == "user"
        role_label = "Learner" if is_learner else "AI"
        role_bg    = "#FEE8EC" if is_learner else RED_PALE.hexval() if hasattr(RED_PALE,"hexval") else "#FCF0F2"
        role_fg    = "#C8102E" if is_learner else "#5C0915"
        row_bg     = "#FFFAFA" if is_learner else WHITE

        tr_rows.append([
            Paragraph(f"<b>{role_label}</b>", ParagraphStyle(
                "trl", fontName="Helvetica-Bold", fontSize=8,
                textColor=colors.HexColor(role_fg), alignment=TA_CENTER,
            )),
            Paragraph(msg.content, ParagraphStyle(
                "trc", fontName="Helvetica", fontSize=8.5,
                textColor=GREY, leading=13,
            )),
        ])

    trt = Table(tr_rows, colWidths=[W*0.14, W*0.86])
    trt.setStyle(TableStyle([
        ("BACKGROUND",    (0,0),(-1,0),  RED_DARK),
        ("TEXTCOLOR",     (0,0),(-1,0),  WHITE),
        ("ROWBACKGROUNDS",(0,1),(-1,-1), [RED_PALE, WHITE]),
        ("VALIGN",        (0,0),(-1,-1), "TOP"),
        ("ALIGN",         (0,0),(0,-1),  "CENTER"),
        ("BOX",           (0,0),(-1,-1), 0.5, BD),
        ("INNERGRID",     (0,0),(-1,-1), 0.3, BD),
        ("TOPPADDING",    (0,0),(-1,-1), 6),
        ("BOTTOMPADDING", (0,0),(-1,-1), 6),
        ("LEFTPADDING",   (0,0),(-1,-1), 6),
        ("RIGHTPADDING",  (0,0),(-1,-1), 6),
    ]))

    story.append(section_header("Conversation Transcript"))
    story.append(Spacer(1, 1))
    story.append(trt)
    story.append(Spacer(1, 8*mm))

    # ════════════════════════════════════════════════════════════════
    # BUILD
    # ════════════════════════════════════════════════════════════════
    def make_canvas(*args, **kwargs):
        return BrandedCanvas(*args, report_title=report.scenario_title, **kwargs)

    doc.build(story, canvasmaker=make_canvas)
    return buf.getvalue()


# ── Standalone test ───────────────────────────────────────────────
if __name__ == "__main__":
    from types import SimpleNamespace

    report = SimpleNamespace(
        scenario_title="Soothing an Angry Customer Over Delayed Delivery",
        learner_role="Customer Service Representative",
        ai_character="Emma Johnson, Upset Client",
        difficulty="Intermediate",
        language="English",
        mode="voice",
        duration_seconds=272,
        turns_completed=4,
        generated_at="2026-04-18T14:30:00Z",
        overall_score=4.5,
        verdict="needs_improvement",
        dimensions=[
            SimpleNamespace(name="De-escalation",              score=40, level="low"),
            SimpleNamespace(name="Empathy & Active Listening",  score=50, level="mid"),
            SimpleNamespace(name="Communication Clarity",       score=30, level="low"),
            SimpleNamespace(name="Compliance & Professionalism",score=60, level="mid"),
            SimpleNamespace(name="Assertiveness",               score=20, level="low"),
            SimpleNamespace(name="Problem Resolution",          score=30, level="low"),
        ],
        feedback=[
            SimpleNamespace(type="strength",   text="The learner attempted to apologize, showing some level of empathy."),
            SimpleNamespace(type="strength",   text="The learner maintained a professional tone throughout the interaction."),
            SimpleNamespace(type="weakness",   text="The learner failed to provide specific information or a timeline to the customer."),
            SimpleNamespace(type="weakness",   text="The learner's responses were vague and did not address the customer's concerns effectively."),
            SimpleNamespace(type="suggestion", text="Provide clear and specific information about the steps being taken to resolve the issue."),
            SimpleNamespace(type="suggestion", text="Improve active listening skills to better understand and address customer concerns."),
        ],
        transcript=[
            SimpleNamespace(role="user",      content="[session_start]"),
            SimpleNamespace(role="assistant", content="I've been waiting to hear back about the delay in my shipment, and honestly, it's frustrating not to have any follow-up. This is an important delivery for my business, and I need to know what went wrong and when I can expect it."),
            SimpleNamespace(role="user",      content="Yeah I've been waiting for here to back about the delay in my shipment and honestly you are frustrated I apologize for that so just allow me some time I'll get back to you soon."),
            SimpleNamespace(role="assistant", content="I appreciate the apology, but I've already been waiting without any updates. I need more than just another promise to get back to me. What specific steps are you taking to resolve this, and when can I expect my shipment to arrive?"),
            SimpleNamespace(role="user",      content="Yeah hi but your shipping will be immediately it will come to your place no need to worry about this."),
            SimpleNamespace(role="assistant", content="I understand you're trying to help, but I need more than reassurance. I need a specific timeline and details on how you're ensuring this won't happen again. Can you provide me with a clear update, please?"),
        ],
    )

    pdf_bytes = generate_pdf(report)
    with open("/mnt/user-data/outputs/report_sample.pdf", "wb") as f:
        f.write(pdf_bytes)
    print("Done — report_sample.pdf written")