"""Extract the bookmark/outline structure from a PDF opened with pdfplumber."""

import pdfplumber


def extract_pdf_bookmarks(pdf: pdfplumber.PDF) -> list[dict]:
    """Extract bookmarks/outlines from an open pdfplumber PDF object.

    Args:
        pdf: An open pdfplumber.PDF object.

    Returns:
        list[dict]: List of {"level": int, "title": str, "page_num": int | None}.
                    Level is clamped to [1, 6]. Returns empty list if no outlines.
    """
    try:
        outlines = pdf.doc.get_outlines()
    except Exception:
        return []

    if not outlines:
        return []

    # Build objid -> page_number mapping
    objid_to_page: dict[int, int] = {}
    for i, page in enumerate(pdf.pages):
        try:
            obj = page.page_obj
            objid_to_page[obj.objid] = i + 1  # 1-indexed page numbers
        except Exception:
            pass

    bookmarks = []
    for item in outlines:
        try:
            level = item[0]  # integer level from get_outlines
            title = item[1]
            dest = item[2]  # destination: page object or list

            # Clamp level to [1, 6]
            level = max(1, min(6, level))

            # Resolve destination to page number
            page_num = None
            if dest is not None:
                if isinstance(dest, list) and len(dest) > 0:
                    # dest[0] is the page object
                    page_obj = dest[0]
                    try:
                        page_num = objid_to_page.get(page_obj.objid)
                    except Exception:
                        pass
                else:
                    try:
                        page_num = objid_to_page.get(dest.objid)
                    except Exception:
                        pass

            bookmarks.append({"level": level, "title": str(title), "page_num": page_num})
        except Exception:
            continue

    return bookmarks
