# smfc 風・温度→ファンレベル変換関数（Python 実装例）

def calc_fan_level(
    temp: float,
    min_temp: float = 30.0,
    max_temp: float = 60.0,
    min_level: int = 35,
    max_level: int = 100,
    steps: int = 6,
) -> int:
    """線形制御関数: 温度をファンレベル(%)に変換する"""
    if temp <= min_temp:
        return min_level
    if temp >= max_temp:
        return max_level
    ratio = (temp - min_temp) / (max_temp - min_temp)
    step_val = round(ratio * steps) / steps
    level = min_level + step_val * (max_level - min_level)
    return int(min(max_level, max(min_level, level)))


def calc_fan_level_multiseg(
    temp: float,
    control_points: list[tuple[float, int]],
    steps: int = 5,
) -> int:
    """多区間制御関数: control_function= 相当の折れ線カーブ"""
    control_points = sorted(control_points, key=lambda x: x[0])
    if temp <= control_points[0][0]:
        return control_points[0][1]
    if temp >= control_points[-1][0]:
        return control_points[-1][1]
    for i in range(len(control_points) - 1):
        t0, l0 = control_points[i]
        t1, l1 = control_points[i + 1]
        if t0 <= temp <= t1:
            ratio = (temp - t0) / (t1 - t0)
            step_val = round(ratio * steps) / steps
            level = l0 + step_val * (l1 - l0)
            return int(min(100, max(0, level)))
    return control_points[-1][1]


# 使用例
if __name__ == "__main__":
    # 線形制御
    for t in [30, 40, 50, 60, 70]:
        print(f"linear  {t}°C -> {calc_fan_level(t)}%")

    # 多区間制御 (control_function=30-35, 50-40, 60-90, 65-100)
    points = [(30, 35), (50, 40), (60, 90), (65, 100)]
    for t in [30, 40, 50, 55, 60, 65, 70]:
        print(f"multiseg {t}°C -> {calc_fan_level_multiseg(t, points)}%")
