"""通用 UCD323/UCDController 辅助函数。

封装"按当前接口取 tx 模块"、"读取分辨率"、"发送图片 Pattern"等所有
测试模块共用的低层 UCD 操作，避免在多个业务模块中重复 if/else。
"""

import UniTAP


def get_tx_modules(ucd):
    """根据当前接口返回 (pg, ag) 模块。

    兼容 UCD323Controller（多接口，含 current_interface 属性）
    与老的 UCDController（仅 HDMI）。
    """
    interface = getattr(ucd, "current_interface", None)
    if interface in (None, "HDMI"):
        return ucd.role.hdtx.pg, ucd.role.hdtx.ag
    if interface in ("DP", "Type-C"):
        return ucd.role.dptx.pg, ucd.role.dptx.ag
    raise ValueError(f"不支持的接口类型: {interface}")


def get_current_resolution(ucd, default=(3840, 2160)):
    """从 UCD 当前 timing 获取 (width, height)，失败时返回 default。"""
    try:
        pg, _ = get_tx_modules(ucd)
        vm = pg.get_vm()
        timing = getattr(vm, "timing", None)
        if timing and hasattr(timing, "h_active") and hasattr(timing, "v_active"):
            return timing.h_active, timing.v_active
    except Exception:
        pass

    timing = getattr(ucd, "current_timing", None)
    if timing and hasattr(timing, "h_active") and hasattr(timing, "v_active"):
        return timing.h_active, timing.v_active

    return default


def send_image_pattern(ucd, image_path, *, bpc=8, color_format=None, colorimetry=None):
    """通过 UCD 发送一张本地图片作为显示 Pattern。

    自动停止音频以避免蜂鸣声。颜色参数留空时使用 RGB / sRGB 默认值。
    返回 True/False。
    """
    if not getattr(ucd, "status", False):
        return False

    try:
        pg, ag = get_tx_modules(ucd)
    except Exception:
        return False

    try:
        ag.stop_generate()
    except Exception:
        pass

    color_mode = UniTAP.ColorInfo()
    color_mode.color_format = color_format or UniTAP.ColorInfo.ColorFormat.CF_RGB
    color_mode.bpc = bpc
    color_mode.colorimetry = colorimetry or UniTAP.ColorInfo.Colorimetry.CM_sRGB

    timing = None
    try:
        vm = pg.get_vm()
        timing = getattr(vm, "timing", None)
    except Exception:
        pass

    try:
        if timing:
            pg.set_vm(vm=UniTAP.VideoMode(timing=timing, color_info=color_mode))
        pg.set_pattern(pattern=image_path)
        pg.apply()
        return True
    except Exception:
        return False
