#!/usr/bin/env python3
import argparse
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# 光速
c = 3.0e8
plt.rcParams["font.family"] = "MS Gothic"

# 任意の運動関数: 例として加速度運動 (ユーザーが自由に書き換え可能)
def x1_pos(t):
    # 例: 初速度 v0=0.5c、加速度 a=0.1c/s
    v0 = 0.5 * c
    a = 0.1 * c
    return v0 * t + 0.5 * a * t**2

def velocity(t, dt=1e-6):
    """数値微分で速度を計算"""
    return (x1_pos(t+dt) - x1_pos(t-dt)) / (2*dt)

def main():
    parser = argparse.ArgumentParser(
        description="任意運動するS1系のミンコフスキー図アニメーション"
    )
    parser.add_argument("dt", type=float, help="観測する時間範囲 [s]")
    args = parser.parse_args()

    dt = args.dt
    t_vals = np.linspace(0, dt, 500)

    # x/c を横軸、t を縦軸に（光秒単位）
    x_over_c = x1_pos(t_vals) / c
    ct_vals = t_vals

    # 固有時 τ の計算
    v_vals = velocity(t_vals)
    gamma_inv = np.sqrt(1 - (v_vals/c)**2)
    tau_vals = np.cumsum(gamma_inv * np.gradient(t_vals))

    # プロット準備
    fig, ax = plt.subplots()
    ax.set_xlabel("x/c [s]")
    ax.set_ylabel("t [s]")
    ax.set_title("加速度運動するS1の時空図")
    ax.grid(True)

    # 光円錐
    ax.plot(ct_vals, ct_vals, "k--", alpha=0.5)
    ax.plot(-ct_vals, ct_vals, "k--", alpha=0.5)

    # S1の世界線
    line_world, = ax.plot([], [], "r-", label="S1の世界線")
    point, = ax.plot([], [], "ro")
    time_text = ax.text(0.05, 0.9, "", transform=ax.transAxes)

    ax.legend()

    def init():
        line_world.set_data([], [])
        point.set_data([], [])
        time_text.set_text("")
        return line_world, point, time_text

    def update(frame):
        t_now = t_vals[:frame]
        x_now = x_over_c[:frame]
        tau_now = tau_vals[:frame]

        line_world.set_data(x_now, t_now)
        point.set_data(x_now[-1], t_now[-1])
        time_text.set_text(
            f"S系時刻 t = {t_now[-1]:.2f} s\nS1系固有時 τ = {tau_now[-1]:.2f} s"
        )
        return line_world, point, time_text

    ani = FuncAnimation(fig, update, frames=len(t_vals),
                        init_func=init, interval=30, blit=True)

    plt.show()

if __name__ == "__main__":
    main()
