"""레이더 차트 생성"""
from io import BytesIO
import matplotlib.pyplot as plt
import numpy as np

from ..data_models import ChartData
from ..pdf.styles import CHART_COLORS
from .combo_chart import setup_japanese_font


def create_radar_chart(chart_data: ChartData) -> BytesIO:
    """레이더 차트 생성

    Args:
        chart_data: 차트 데이터

    Returns:
        PNG 이미지 바이트 버퍼
    """
    setup_japanese_font()

    labels = chart_data.labels
    num_vars = len(labels)

    # 각도 계산
    angles = np.linspace(0, 2 * np.pi, num_vars, endpoint=False).tolist()
    angles += angles[:1]  # 닫힌 도형을 위해 첫 번째 각도 추가

    fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True))

    for i, dataset in enumerate(chart_data.datasets):
        data = dataset.get("data", [])
        color = dataset.get("color", CHART_COLORS[i % len(CHART_COLORS)])
        label = dataset.get("label", f"Series {i+1}")

        # 데이터 닫기
        values = data + data[:1]

        ax.plot(
            angles,
            values,
            color=color,
            linewidth=2,
            label=label,
        )
        ax.fill(
            angles,
            values,
            color=color,
            alpha=0.25,
        )

    # 축 레이블 설정
    ax.set_xticks(angles[:-1])
    ax.set_xticklabels(labels, fontsize=10)

    # Y축 설정
    ax.set_ylim(0, 100)
    ax.set_yticks([20, 40, 60, 80, 100])
    ax.set_yticklabels(["20%", "40%", "60%", "80%", "100%"], fontsize=8)

    # 그리드
    ax.grid(True, alpha=0.3)

    # 범례
    ax.legend(loc="upper right", bbox_to_anchor=(1.3, 1.0), fontsize=8)

    # 타이틀
    if chart_data.title:
        plt.title(chart_data.title, fontsize=12, fontweight="bold", y=1.08)

    plt.tight_layout()

    # 이미지로 저장
    buffer = BytesIO()
    plt.savefig(buffer, format="png", dpi=150, bbox_inches="tight")
    buffer.seek(0)
    plt.close(fig)

    return buffer
