import pymupdf


def make_pdf(pages: list[str]) -> bytes:
    """pages: 'text' | 'blank' | 'ruled' | 'faint' | 'shortfaint' | 'showthrough'. A4 portrait."""
    doc = pymupdf.open()
    for kind in pages:
        p = doc.new_page(width=595, height=842)
        if kind in ("ruled", "faint", "text"):
            for y in range(80, 800, 24):                      # printed ruled lines, light grey
                p.draw_line((40, y), (555, y), color=(0.75, 0.75, 0.75), width=0.6)
        if kind == "text":
            for i, y in enumerate(range(100, 700, 24)):
                p.insert_text((60, y), f"Answer line {i}: the cell is the basic unit of life.", fontsize=13)
        if kind == "faint":
            for y in range(100, 220, 24):
                p.insert_text((60, y), "faint pencil writing here", fontsize=12, color=(0.62, 0.62, 0.62))
        if kind == "shortfaint":                              # e.g. the last line of a calculation
            p.insert_text((60, 100), "= 5 cm", fontsize=12, color=(0.7, 0.7, 0.7))
        if kind == "showthrough":
            for y in range(100, 700, 24):                     # very light mirrored ink from the back side
                p.insert_text((60, y), "reverse side text bleeding", fontsize=13, color=(0.93, 0.93, 0.93))
    return doc.tobytes()


def make_bn_answer_pdf(lines_per_page: list[list[str]]) -> tuple[bytes, list[list[list[float]]]]:
    """A4 pages with Bengali/English text at fixed line positions (stand-in for handwriting).
    Returns the PDF bytes and, per page, the normalized bbox of each line."""
    from aix.pipeline.textrun import CSS, FONT_DIR, spans
    arch = pymupdf.Archive(FONT_DIR)
    doc = pymupdf.open()
    boxes = []
    for lines in lines_per_page:
        p = doc.new_page(width=595, height=842)
        for y in range(80, 800, 28):
            p.draw_line((40, y), (555, y), color=(0.8, 0.85, 0.9), width=0.5)
        page_boxes = []
        for i, text in enumerate(lines):
            y0 = 58 + i * 28
            width = min(60 + 9.5 * len(text), 500)
            r = pymupdf.Rect(48, y0, 48 + width, y0 + 22)
            p.insert_htmlbox(r, f"<p>{spans(text)}</p>", css=CSS + "*{font-size:15px;color:#1a237e;}", archive=arch)
            page_boxes.append([r.x0 / 595, r.y0 / 842, r.x1 / 595, r.y1 / 842])
        boxes.append(page_boxes)
    return doc.tobytes(), boxes
