"""
fitting
直線・曲線近似の共通ユーティリティモジュール
"""

import numpy as np


def theil_sen_fit(
    y: np.ndarray,
    x: np.ndarray,
) -> tuple[float, float]:
    """Theil-Sen 推定で直線 x = slope * y + intercept を求める

    全ペアの傾きの中央値を使い，外れ値に強い直線近似を行う

    Args:
        y: y 座標の配列（行番号）
        x: x 座標の配列（各行の中心）

    Returns:
        (slope, intercept) のタプル
    """
    n = len(y)
    slopes = []
    for i in range(n):
        for j in range(i + 1, n):
            dy = y[j] - y[i]
            if dy != 0:
                slopes.append((x[j] - x[i]) / dy)

    if len(slopes) == 0:
        return 0.0, float(np.median(x))

    slope = float(np.median(slopes))
    intercept = float(np.median(x - slope * y))
    return slope, intercept
