# exams/utils/pdf/autofit.py
from reportlab.platypus import Table
from reportlab.lib.pagesizes import A4

# Page width minus left/right margins (we'll assume 20pt margins each side)
PAGE_USABLE_WIDTH = A4[0] - 40

def autofit(data, max_width=PAGE_USABLE_WIDTH):
    """
    Make each row have same number of columns and return a Table
    with evenly distributed column widths across max_width.
    This is intentionally simple and very stable for shared hosts.
    """
    if not data:
        return Table([[]])

    # Determine maximum columns in any row
    col_count = max(len(r) for r in data)

    # Normalize all rows to same column count
    normalized = []
    for r in data:
        if len(r) < col_count:
            r = r + [''] * (col_count - len(r))
        normalized.append(r)

    # Use even column width distribution
    col_width = max_width / float(col_count)
    col_widths = [col_width] * col_count

    tbl = Table(normalized, colWidths=col_widths)
    return tbl
