from __future__ import annotations

import copy
from dataclasses import dataclass

from app.data_range_converter import convert_pattern_params
from drivers.ucd_helpers import send_solid_rgb_pattern


@dataclass
class PatternSession:
    mode: str
    test_type: str
    active_config: object
    pattern_params: list[list[int]]
    total_patterns: int
    display_names: list[str]


class PatternService:
    def __init__(self, app):
        self.app = app

    def prepare_session(self, mode, *, test_type=None, log_details=False):
        test_type = test_type or self.app.config.current_test_type
        if not self.app.config.set_current_pattern(mode):
            raise ValueError(f"未知的图案模式: {mode}")

        active_config = self.app.config
        source_params = self._get_source_pattern_params(mode)

        if test_type == "screen_module":
            if log_details:
                self._log("=" * 50, "separator")
                self._log("设置屏模组信号格式:", "info")
                self._log("=" * 50, "separator")
                self._log(
                    f"  Timing: {self.app.config.current_test_types[test_type]['timing']}",
                    "info",
                )
            self.app.ucd.set_ucd_params(active_config)
        elif test_type == "sdr_movie":
            active_config = self._prepare_video_session(
                mode=mode,
                test_type=test_type,
                source_params=source_params,
                data_range=self.app.sdr_data_range_var.get(),
                log_title="设置 SDR 信号格式:",
                setup_message=f"设置 SDR 测试图案（{mode} 模式）..."
                if mode != "accuracy"
                else "设置 SDR 29色色准测试图案...",
                setup_format=lambda: self.app.ucd.set_sdr_format(
                    color_space=self.app.sdr_color_space_var.get(),
                    gamma=self.app.sdr_gamma_type_var.get(),
                    data_range=self.app.sdr_data_range_var.get(),
                    bit_depth=self.app.sdr_bit_depth_var.get(),
                ),
                log_items=[
                    ("色彩空间", self.app.sdr_color_space_var.get()),
                    ("Gamma", self.app.sdr_gamma_type_var.get()),
                    ("数据范围", self.app.sdr_data_range_var.get()),
                    ("编码位深", self.app.sdr_bit_depth_var.get()),
                ],
                log_details=log_details,
            )
        elif test_type == "hdr_movie":
            active_config = self._prepare_video_session(
                mode=mode,
                test_type=test_type,
                source_params=source_params,
                data_range=self.app.hdr_data_range_var.get(),
                log_title="设置 HDR 信号格式:",
                setup_message=f"设置 HDR 测试图案（{mode} 模式）..."
                if mode != "accuracy"
                else "设置 HDR 29色色准测试图案...",
                setup_format=lambda: self.app.ucd.set_hdr_format(
                    color_space=self.app.hdr_color_space_var.get(),
                    data_range=self.app.hdr_data_range_var.get(),
                    bit_depth=self.app.hdr_bit_depth_var.get(),
                    max_cll=self.app.hdr_maxcll_var.get(),
                    max_fall=self.app.hdr_maxfall_var.get(),
                ),
                log_items=[
                    ("色彩空间", self.app.hdr_color_space_var.get()),
                    ("数据范围", self.app.hdr_data_range_var.get()),
                    ("编码位深", self.app.hdr_bit_depth_var.get()),
                    ("MaxCLL", self.app.hdr_maxcll_var.get()),
                    ("MaxFALL", self.app.hdr_maxfall_var.get()),
                ],
                log_details=log_details,
            )
        else:
            raise ValueError(f"不支持的测试类型: {test_type}")

        pattern_params = copy.deepcopy(active_config.current_pattern["pattern_params"])
        return PatternSession(
            mode=mode,
            test_type=test_type,
            active_config=active_config,
            pattern_params=pattern_params,
            total_patterns=len(pattern_params),
            display_names=self._get_display_names(mode, len(pattern_params)),
        )

    def send_session_pattern(self, session, index):
        if index < 0 or index >= session.total_patterns:
            raise IndexError(f"pattern 索引越界: {index}")

        pattern_param = session.pattern_params[index]
        if not self.app.ucd.send_current_pattern_params(pattern_param):
            raise RuntimeError(f"发送 pattern 失败: {index}")
        return pattern_param

    def send_rgb(self, rgb, *, session=None, test_type=None):
        active_session = session or self.prepare_session(
            "rgb",
            test_type=test_type,
            log_details=False,
        )
        converted_rgb = self._convert_rgb_for_test_type(rgb, active_session.test_type)
        send_solid_rgb_pattern(self.app.ucd, converted_rgb, raise_on_error=True)
        return True

    def _prepare_video_session(
        self,
        *,
        mode,
        test_type,
        source_params,
        data_range,
        log_title,
        setup_message,
        setup_format,
        log_items,
        log_details,
    ):
        if log_details:
            self._log("=" * 50, "separator")
            self._log(log_title, "info")
            self._log("=" * 50, "separator")
            for label, value in log_items:
                self._log(f"  {label}: {value}", "info")

        success = setup_format()
        if log_details:
            self._log(
                f"{test_type.split('_')[0].upper()} 信号格式设置{'成功' if success else '失败'}",
                "success" if success else "error",
            )
            self._log(setup_message, "info")

        converted_params = convert_pattern_params(
            pattern_params=source_params,
            data_range=data_range,
            verbose=False,
        )
        active_config = self.app.config.get_temp_config_with_converted_params(
            mode=mode,
            converted_params=converted_params,
        )
        self.app.ucd.set_ucd_params(active_config)

        if log_details:
            self._log(f"图案参数已设置，共 {len(converted_params)} 个图案", "success")

        return active_config

    def _get_source_pattern_params(self, mode):
        config = self.app.config
        if mode == "rgb":
            return copy.deepcopy(config.default_pattern_rgb["pattern_params"])
        if mode == "gray":
            return copy.deepcopy(config.default_pattern_gray["pattern_params"])
        if mode == "accuracy":
            return copy.deepcopy(config.default_pattern_accuracy["pattern_params"])
        if mode == "custom":
            return copy.deepcopy(config.default_pattern_temp["pattern_params"])
        raise ValueError(f"未知的图案模式: {mode}")

    def _get_display_names(self, mode, total_patterns):
        if mode == "accuracy":
            return self.app.config.get_accuracy_color_names()
        if mode == "custom" and hasattr(self.app.config, "get_temp_pattern_names"):
            return self.app.config.get_temp_pattern_names()
        return [f"P {index + 1}" for index in range(total_patterns)]

    def _convert_rgb_for_test_type(self, rgb, test_type):
        if test_type == "sdr_movie":
            data_range = self.app.sdr_data_range_var.get()
        elif test_type == "hdr_movie":
            data_range = self.app.hdr_data_range_var.get()
        else:
            data_range = "Full"

        return convert_pattern_params([list(rgb)], data_range=data_range, verbose=False)[0]

    def _log(self, message, level):
        if hasattr(self.app, "log_gui"):
            self.app.log_gui.log(message, level=level)