#!/usr/bin/env python3
"""
概要:
    Excelファイルからデータを読み込み、多項式最小二乗法でフィッティングを行うスクリプトです。

詳細説明:
    コマンドライン引数で入力Excelファイルと多項式の次数を受け取ります。
    pandasを使ってデータを読み込み、numpy.polyfitで多項式近似を行います。
    結果はCSVファイルとして出力され、グラフが表示されます。

関連リンク:
    lsq_polynomial_usage
"""

import sys
from pathlib import Path

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


def main():
    """
    概要:
        多項式最小二乗法フィッティングのメイン処理を実行します。

    詳細説明:
        コマンドライン引数を解析し、データの読み込み、numpy.polyfitによる
        フィッティング、決定係数の計算、CSV出力、グラフ描画を行います。
        引数が足りない場合は使用方法を表示してスクリプトを終了します。
    """

    if len(sys.argv) < 3:
        print("Usage:")
        print("  python lsq_polynomial.py data.xlsx order")
        sys.exit(1)

    infile = sys.argv[1]
    degree = int(sys.argv[2])

    outfile = Path(infile).stem + "_fit.csv"

    # Excel読込み
    df = pd.read_excel(infile)

    x = df.iloc[:, 0].to_numpy()
    y = df.iloc[:, 1].to_numpy()

    # 多項式最小二乗法
    coeffs = np.polyfit(x, y, degree)

    # Polynomialオブジェクト作成
    poly = np.poly1d(coeffs)

    # 近似値計算
    y_fit = poly(x)

    # 決定係数 R²
    ss_res = np.sum((y - y_fit) ** 2)
    ss_tot = np.sum((y - np.mean(y)) ** 2)
    r2 = 1.0 - ss_res / ss_tot

    # 結果表示
    print()
    print(f"Input file : {infile}")
    print(f"Order      : {degree}")
    print()
    print("Polynomial:")
    print(poly)
    print()
    print(f"R² = {r2:.6f}")
    print()

    # CSV出力
    result = pd.DataFrame({
        "x": x,
        "y": y,
        "y_fit": y_fit
    })

    result.to_csv(outfile, index=False)

    print(f"Saved : {outfile}")

    # 滑らかな曲線描画用
    x_plot = np.linspace(x.min(), x.max(), 1000)
    y_plot = poly(x_plot)

    # Plot
    plt.figure(figsize=(8, 6))

    plt.scatter(
        x,
        y,
        label="Data",
        color="tab:blue"
    )

    plt.plot(
        x_plot,
        y_plot,
        label=f"Polynomial (n={degree})",
        color="tab:red"
    )

    plt.xlabel("x")
    plt.ylabel("y")
    plt.title("Polynomial Least-Squares Fit")
    plt.legend()
    plt.grid(True)

    plt.tight_layout()
    plt.show()


if __name__ == "__main__":
    main()