"""EOTF 曲线绘制（HDR）。

Step 2 重构：从 pqAutomationApp.PQAutomationApp.plot_eotf 原样搬迁。
"""

import numpy as np
from app.views.modern_styles import get_theme_palette

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from pqAutomationApp import PQAutomationApp



def plot_eotf(self: "PQAutomationApp", L_bar, results_with_eotf_list, test_type):
    """绘制 EOTF 曲线 + 数据表格（HDR 专用，包含实测亮度）"""
    palette = get_theme_palette()

    # ========== 1. 清空并重置左侧曲线 ==========
    self.eotf_ax.clear()
    self.eotf_fig.patch.set_facecolor(palette["bg"])
    self.eotf_ax.set_facecolor(palette["card_bg"])
    self.eotf_ax.set_xlim(0, 105)
    self.eotf_ax.set_ylim(0, 1.1)
    self.eotf_ax.set_xlabel("灰阶 (%)", fontsize=10)
    self.eotf_ax.set_ylabel("L_bar", fontsize=10)
    self.eotf_ax.grid(True, linestyle="--", alpha=0.3)
    self.eotf_ax.tick_params(labelsize=9)
    self.eotf_ax.tick_params(colors=palette["fg"])
    for spine in self.eotf_ax.spines.values():
        spine.set_color(palette["border"])

    # 生成横坐标（灰阶百分比）
    x_values = np.linspace(0, 100, len(L_bar))

    # 反转 L_bar
    if len(L_bar) > 1 and L_bar[0] > L_bar[-1]:
        L_bar = L_bar[::-1]
        results_with_eotf_list = results_with_eotf_list[::-1]

    # 计算平均 EOTF Gamma
    eotf_values = []
    for item in results_with_eotf_list:
        if isinstance(item, (list, tuple)) and len(item) >= 4:
            eotf = item[3]
            if 0.5 < eotf < 5.0:
                eotf_values.append(eotf)

    avg_eotf = np.mean(eotf_values) if eotf_values else 2.2

    # 绘制实测曲线
    self.eotf_ax.plot(
        x_values,
        L_bar,
        "b-o",
        label=f"实测 (平均γ={avg_eotf:.2f})",
        linewidth=2,
        markersize=4,
        zorder=5,
    )

    # 绘制 PQ (ST.2084) 理想曲线
    pq_L_bar = self.calculate_pq_curve(x_values)
    self.eotf_ax.plot(
        x_values,
        pq_L_bar,
        "r--",
        label="理想 PQ (ST.2084)",
        linewidth=2,
        alpha=0.7,
        zorder=3,
    )

    # 图例
    self.eotf_ax.legend(fontsize=9, loc="upper left", framealpha=0.95)

    # ========== 2. 清空并绘制右侧表格 ==========
    self.eotf_table_ax.clear()
    self.eotf_table_ax.axis("off")

    # 构建表格数据（4列）
    table_data = [["灰阶", "实测亮度\n(cd/m²)", "L_bar", "EOTF γ"]]

    for i, (x_val, L_val, result) in enumerate(
        zip(x_values, L_bar, results_with_eotf_list)
    ):
        # 提取实测亮度
        if isinstance(result, (list, tuple)) and len(result) >= 3:
            measured_lv = result[2]
            measured_lv_str = f"{measured_lv:.2f}"
        else:
            measured_lv_str = "--"

        # 提取 EOTF
        if isinstance(result, (list, tuple)) and len(result) >= 4:
            eotf = result[3]
            if eotf < 0.5 or eotf > 5.0:
                eotf_str = "--"
            else:
                eotf_str = f"{eotf:.2f}"
        else:
            eotf_str = "--"

        table_data.append(
            [
                f"{x_val:.0f}%",
                measured_lv_str,
                f"{L_val:.3f}",
                eotf_str,
            ]
        )

    # 绘制表格（4列）
    table = self.eotf_table_ax.table(
        cellText=table_data,
        cellLoc="center",
        loc="center",
        colWidths=[0.18, 0.28, 0.27, 0.27],
    )

    # 美化表格
    table.auto_set_font_size(False)
    table.set_fontsize(7.5)
    table.scale(1, 1.5)

    # 表头样式
    for i in range(4):
        cell = table[(0, i)]
        cell.set_facecolor(palette["primary"])
        cell.set_text_props(weight="bold", color=palette["select_fg"])

    # 数据行交替颜色
    for i in range(1, len(table_data)):
        for j in range(4):
            cell = table[(i, j)]
            if i % 2 == 0:
                cell.set_facecolor(palette["surface_alt_bg"])
            else:
                cell.set_facecolor(palette["card_bg"])

    # ========== 3. 总标题 ==========
    test_type_name = self.get_test_type_name(test_type)
    self.eotf_fig.suptitle(
        f"{test_type_name} - EOTF 曲线（PQ ST.2084）",
        fontsize=12,
        y=0.98,
        fontweight="bold",
        color=palette["fg"],
    )

    # 选中 EOTF Tab
    try:
        eotf_tab_id = str(self.eotf_chart_frame)
        current_tabs = list(self.chart_notebook.tabs())
        if eotf_tab_id in current_tabs:
            eotf_index = current_tabs.index(eotf_tab_id)
            self.chart_notebook.select(eotf_index)
    except:
        pass

    self.log_gui.log("EOTF 曲线 + 数据表格绘制完成", level="success")


class PlotEotfMixin:
    """由 tools/refactor_to_mixins.py 自动生成。
    把本模块的自由函数挂到 PQAutomationApp 上，便于 F12 跳转与类型推断。
    """
    plot_eotf = plot_eotf
