import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from datetime import date, datetime, timedelta
import tkinter as tk
from tkinter import messagebox
from tkcalendar import DateEntry
import math  # 正確な計算のためにmathを再導入

# --- 1. 定数とロジック定義 ---
def get_status_guide(val):
    if val > 0.5:
        return "高調期（絶好調！積極的な行動がおすすめ）"
    elif val < -0.5:
        return "低調期（無理は禁物。リラックスを意識）"
    elif -0.1 <= val <= 0.1:
        return "注意日（バランスが不安定。慎重に過ごして）"
    elif val > 0:
        return "上昇中（徐々に調子が上がっています）"
    else:
        return "下降中（疲れが溜まりやすい時期です）"

# 【修正】最初のシンプルなコードと完全に一致する正確な計算式に変更
def calculate_biorhythm_single(days):
    p = math.sin(2 * math.pi * days / 23)
    e = math.sin(2 * math.pi * days / 28)
    i = math.sin(2 * math.pi * days / 33)
    return p, e, i

# --- 2. メインの処理関数 ---
def update_all():
    try:
        # 入力値の取得
        birth_dt = birth_cal.get_date()
        target_dt = target_cal.get_date()

        # 判定日のデータ
        today_elapsed = (target_dt - birth_dt).days
        p_today, e_today, i_today = calculate_biorhythm_single(today_elapsed)

        # グローバル変数にテキストを保存（メッセージボックス用）
        global current_msg
        current_msg = (
            f"【指定日のバイオリズム診断】 {target_dt}\n"
            f"--------------------------------------------------\n"
            f"■ 身体 (23日周期): {p_today:+.2f} -> {get_status_guide(p_today)}\n"
            f"■ 感情 (28日周期): {e_today:+.2f} -> {get_status_guide(e_today)}\n"
            f"■ 知性 (33日周期): {i_today:+.2f} -> {get_status_guide(i_today)}"
        )

        # グラフデータ作成（前後15日間）
        days_range = range(-15, 16)
        dates = [target_dt + timedelta(days=d) for d in days_range]

        # 【修正】1日ずつ確実に最初の計算式を通すように変更
        physical, emotional, intellectual = [], [], []
        for d in dates:
            elapsed = (d - birth_dt).days
            p, e, i = calculate_biorhythm_single(elapsed)
            physical.append(p)
            emotional.append(e)
            intellectual.append(i)

        # グラフの再描画
        ax.clear()
        ax.plot(dates, physical, label='Physical', color='red')
        ax.plot(dates, emotional, label='Emotional', color='blue')
        ax.plot(dates, intellectual, label='Intellectual', color='green')

        ax.axhline(0, color='black', linewidth=0.5, linestyle='--')
        ax.axvline(target_dt, color='orange', linewidth=1.5, linestyle='-', label='Selected Day')
        ax.set_title(f"Biorhythm Chart (Birth: {birth_dt})", fontsize=12)
        ax.set_ylim(-1.1, 1.1)
        ax.grid(True, alpha=0.3)
        ax.legend()
        fig.autofmt_xdate()
        canvas.draw()

    except Exception as e:
        messagebox.showerror("エラー", f"計算中にエラーが発生しました:\n{e}")

def show_popup():
    messagebox.showinfo("Biorhythm Guide", current_msg)

# --- 3. GUIウインドウの構築 ---
root = tk.Tk()
root.title("バイオリズムチェッカー")
root.geometry("800x650")

# 入力コントロール用フレーム
input_frame = tk.Frame(root)
input_frame.pack(fill=tk.X, padx=10, pady=10)

# 生年月日入力（カレンダー形式）
tk.Label(input_frame, text="① 生年月日を指定:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
# 修正後のコード
birth_cal = DateEntry(
    input_frame,
    width=12,
    # --- 日付の初期値を2001年1月1日に設定 ---
    year=2001,
    month=1,
    day=1,
    date_pattern='yyyy-mm-dd',

    # --- カラーカスタマイズ（お好みに合わせて変更してください） ---
    background='navy',            # カレンダー上部（年月表示部）の背景色
    foreground='white',           # カレンダー上部の文字色
    headersbackground='gainsboro', # 曜日ヘッダー（月〜日）の背景色
    headersforeground='black',     # 曜日ヘッダーの文字色
    selectbackground='darkorange', # 日付を選択したときのハイライト色
    selectforeground='white',      # 日付を選択したときの文字色
    borderwidth=2
)
birth_cal.grid(row=0, column=1, padx=5, pady=5)

# 判定日入力（カレンダー形式）
tk.Label(input_frame, text="② 調べたい日を指定:").grid(row=0, column=2, padx=5, pady=5, sticky="w")
# 修正後のコード
target_cal = DateEntry(
    input_frame,
    width=12,
    background='darkorange',
    foreground='white',
    borderwidth=2,
    year=date.today().year,
    month=date.today().month,
    day=date.today().day,
    date_pattern='yyyy-mm-dd'  # ← ★これをつけると1956年を正しく認識します
)
target_cal.grid(row=0, column=3, padx=5, pady=5)

# ボタン群
btn_calc = tk.Button(input_frame, text="再計算 & グラフ更新", command=update_all, bg="lightgreen")
btn_calc.grid(row=0, column=4, padx=15, pady=5)

btn_popup = tk.Button(input_frame, text="診断結果をポップアップ表示", command=show_popup, bg="lightcyan")
btn_popup.grid(row=0, column=5, padx=5, pady=5)

# グラフ描画エリアの埋め込み
fig, ax = plt.subplots(figsize=(8, 4.5))
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

# 初期表示
current_msg = ""
update_all()

# アプリ起動
root.mainloop()
