from reportlab.platypus import Table, TableStyle, Paragraph, Spacer
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet

styles = getSampleStyleSheet()


def v(obj, name, default=0):
    """
    Safe value extractor:
    - works for dict
    - works for Django model / SimpleNamespace
    """
    if isinstance(obj, dict):
        return obj.get(name, default)
    return getattr(obj, name, default)
    
def title_block(text, font_size=14):
    return Paragraph(
        f"<b>{text}</b>",
        styles["Title"]
    )


def spacer(h=10):
    return Spacer(1, h)


def bordered_table(data, col_widths, header_rows=1):
    table = Table(data, colWidths=col_widths, repeatRows=header_rows)

    table.setStyle(TableStyle([
        ("GRID", (0, 0), (-1, -1), 1, colors.black),
        ("BACKGROUND", (0, 0), (-1, header_rows - 1), colors.HexColor("#cfeefc")),
        ("ALIGN", (0, 0), (-1, -1), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("FONTNAME", (0, 0), (-1, header_rows - 1), "Helvetica-Bold"),
    ]))
    return table


def colored_row(table, row_index, color):
    return TableStyle([
        ("BACKGROUND", (0, row_index), (-1, row_index), color),
        ("FONTNAME", (0, row_index), (-1, row_index), "Helvetica-Bold"),
    ])
