from __future__ import annotations

from typing import Any, Tuple


def plot_dendrogram(
    df: Any,
    vector_col: str = "vector",
    method: str = "ward",
    figsize: Tuple[int, int] = (15, 8),
    orientation: str = "top",
    distance_sort: str = "descending",
    show_leaf_counts: bool = True,
    color_threshold: float = 18,
    show: bool = True,
):
    """계층적 군집 덴드로그램을 그린 뒤 linkage matrix를 반환합니다.

    Parameters
    ----------
    df:
        pandas DataFrame(또는 유사 객체). `df[vector_col]`에는 벡터가 들어있어야 합니다.
    vector_col:
        벡터 컬럼명
    method:
        scipy linkage method (예: 'ward', 'single', 'complete', 'average')
    figsize:
        그래프 크기
    orientation, distance_sort, show_leaf_counts, color_threshold:
        scipy.cluster.hierarchy.dendrogram 옵션
    show:
        True이면 plt.show()로 즉시 출력합니다.

    Returns
    -------
    linked:
        scipy linkage 결과(링키지 매트릭스)
    """
    from scipy.cluster.hierarchy import dendrogram, linkage
    import matplotlib.pyplot as plt

    linked = linkage(list(df[vector_col]), method)

    plt.figure(figsize=figsize)
    dendrogram(
        linked,
        orientation=orientation,
        distance_sort=distance_sort,
        show_leaf_counts=show_leaf_counts,
        color_threshold=color_threshold,
    )

    if show:
        plt.show()

    return linked
