"""선 차트 생성"""
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_line_chart(chart_data: ChartData) -> BytesIO:
    """선 차트 생성

    Args:
        chart_data: 차트 데이터

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

    fig, ax = plt.subplots(figsize=(10, 5))

    labels = chart_data.labels
    x = np.arange(len(labels))

    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}")
        dashed = dataset.get("dashed", False)

        ax.plot(
            x,
            data,
            color=color,
            label=label,
            marker="o",
            markersize=5,
            linestyle="--" if dashed else "-",
            linewidth=2,
        )

        # 데이터 포인트 레이블
        for j, val in enumerate(data):
            if val != 0:
                ax.annotate(
                    f"{val:.1f}%",
                    (x[j], val),
                    textcoords="offset points",
                    xytext=(0, 8),
                    ha="center",
                    fontsize=8,
                    color=color,
                )

    ax.set_xlabel("")
    ax.set_ylabel("達成率 (%)")
    ax.set_xticks(x)
    ax.set_xticklabels(labels, rotation=45, ha="right")

    # 100% 기준선
    ax.axhline(y=100, color="#9ca3af", linestyle="--", linewidth=1, alpha=0.7)

    # Y축 범위 설정
    all_values = []
    for dataset in chart_data.datasets:
        all_values.extend(dataset.get("data", []))
    if all_values:
        min_val = min(all_values)
        max_val = max(all_values)
        padding = (max_val - min_val) * 0.1 if max_val != min_val else 10
        ax.set_ylim(min_val - padding, max_val + padding)

    # 범례
    ax.legend(loc="upper left", fontsize=8)

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

    # 그리드
    ax.grid(axis="both", alpha=0.3)
    ax.set_axisbelow(True)

    plt.tight_layout()

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

    return buffer
