def merge_links(page: Page, pdf: pdfium.PdfDocument, refs: PageReference):
    """
    Merges links with spans. Some spans can also have multiple links associated with them.
    We break up the spans and reconstruct them taking the links into account.
    """
    page_id = page["page"]

    links = get_links(page_id, pdf)

    spans = [span for block in page['blocks'] for line in block['lines'] for span in line['spans']]
    span_bboxes = [span['bbox'].bbox for span in spans]
    link_bboxes = [link['bbox'] for link in links]

    intersection_matrix = matrix_intersection_area(link_bboxes, span_bboxes)

    span_link_map: Dict[int, List[Link]] = {}
    for link_idx, link in enumerate(links):
        intersection_link = intersection_matrix[link_idx]
        if intersection_link.sum() == 0:
            continue

        max_intersection = intersection_link.argmax()
        span = spans[max_intersection]

        dest_page = link['dest_page']
        if dest_page is not None:
            if link['dest_pos']:
                dest_pos = link['dest_pos']
            else:
                # Don't link to self if there is no dest_pos
                if dest_page == page_id:
                    continue
                # if we don't have a dest pos, we just link to the top of the page
                dest_pos = [0.0, 0.0]

            ref = refs.add_ref(dest_page, dest_pos)
            link['url'] = ref.url

        span_link_map.setdefault(max_intersection, [])
        span_link_map[max_intersection].append(link)

    span_idx = 0
    for block in page["blocks"]:
        for line in block["lines"]:
            spans = []
            for span in line["spans"]:
                if span_idx in span_link_map:
                    spans.extend(_reconstruct_spans(span, span_link_map[span_idx]))
                else:
                    spans.append(span)
                span_idx += 1
            line['spans'] = spans

    Merges links with spans. Some spans can also have multiple links associated with them.
    We break up the spans and reconstruct them taking the links into account.
    
pdftext/pdf/links.py