import tkinter as tk
from tkinter import ttk
import calendar
from datetime import datetime, \
  timedelta

# 祝日情報
HOLIDAYS = {
  (1, 1): "元日",
  (2, 11): "建国記念の日",
  (2, 23): "天皇誕生日",
  (3, 20): "春分の日",
  (4, 29): "昭和の日",
  (5, 3): "憲法記念日",
  (5, 4): "みどりの日",
  (5, 5): "こどもの日",
  (8, 11): "山の日",
  (9, 22): "秋分の日",
  (11, 3): "文化の日",
  (11, 23): "勤労感謝の日",
}

WEEKDAY_HOLIDAYS = {
  (1, 2, 0): "成人の日",
  (7, 3, 0): "海の日",
  (9, 3, 0): "敬老の日",
  (10, 2, 0): "スポーツの日"
}


class CalendarApp(tk.Tk):
  def __init__(self):
    super().__init__()

    self.title("カレンダー（祝日対応）")
    self.geometry("600x550")  # サイズを大きく変更

    self.current_year = datetime.now().year
    self.current_month = datetime.now().month

    self.create_widgets()
    self.display_calendar(self.current_year, self.current_month)

  def create_widgets(self):
    # 年月選択
    self.year_var = tk.IntVar(value=self.current_year)
    self.month_var = tk.IntVar(value=self.current_month)

    year_label = tk.Label(self, text="年")
    year_label.grid(row=0, column=0, padx=5, pady=5)

    self.year_combo = ttk.Combobox(self, textvariable=self.year_var, width=5, 
                                   values=[y for y in range(1900, 2101)])
    self.year_combo.grid(row=0, column=1, padx=5, pady=5)

    month_label = tk.Label(self, text="月")
    month_label.grid(row=0, column=2, padx=5, pady=5)

    self.month_combo = ttk.Combobox(self, 
                                    textvariable=self.month_var, width=3, 
                                    values=[m for m in range(1, 13)])
    self.month_combo.grid(row=0, column=3, padx=5, pady=5)

    show_button = tk.Button(self, text="表示", command=self.update_calendar)
    show_button.grid(row=0, column=4, padx=5, pady=5)

    # カレンダー表示フレーム
    self.calendar_frame = tk.Frame(self)
    self.calendar_frame.grid(row=1, column=0, columnspan=5, pady=10)

  def get_holidays(self, year, month):
    """指定年月の祝日と振替休日を取得"""
    holidays = {}

    # 固定祝日
    for (m, d), name in HOLIDAYS.items():
      if m == month:
        holidays[d] = name

    # 第〇月曜日の祝日
    for (m, week, weekday), name in WEEKDAY_HOLIDAYS.items():
      if m == month:
        c = calendar.Calendar(firstweekday=0)
        month_days = [d for d in c.itermonthdays(year, month) if d != 0]
        weekdays = [day for day in month_days \
                    if datetime(year, month, day).weekday() == weekday]
        if len(weekdays) >= week:
          holidays[weekdays[week - 1]] = name

    # 振替休日処理
    cal = calendar.Calendar(firstweekday=6)  # 日曜スタート
    month_days = cal.monthdayscalendar(year, month)
    
    # 振替休日チェック
    occupied = set(holidays.keys())
    for week in month_days:
      for day in week:
        if day != 0:
          date = datetime(year, month, day)
          if date.weekday() == 6 and day in holidays:  # 日曜日が祝日の場合
            next_day = day + 1
            while next_day in occupied:  # 振替休日が祝日と重複しないように処理
              next_day += 1
            if next_day <= calendar.monthrange(year, month)[1]:
              holidays[next_day] = "振替休日"
              occupied.add(next_day)

    return holidays

  def display_calendar(self, year, month):
    """指定年月のカレンダーを表示"""
    # フレーム内ウィジェット削除
    for widget in self.calendar_frame.winfo_children():
      widget.destroy()

    # 曜日ラベル表示
    days = ["月", "火", "水", "木", "金", "土", "日"]
    for col, day in enumerate(days):
      label = tk.Label(self.calendar_frame, text=day, 
                       font=("Helvetica", 12, "bold"), 
                       borderwidth=0, width=8, height=2)
      label.grid(row=0, column=col)

    # 祝日取得
    holidays = self.get_holidays(year, month)

    # 日付表示
    cal = calendar.Calendar(firstweekday=0)
    month_days = cal.monthdayscalendar(year, month)

    for row, week in enumerate(month_days, start=1):
      for col, day in enumerate(week):
        if day == 0:
          text = ""
        else:
          text = str(day)

        # 祝日や振替休日は青色の円で囲む
        if day in holidays:
          # サイズ拡大で間隔を広げる
          canvas = tk.Canvas(self.calendar_frame, width=70, height=70)  
          canvas.grid(row=row, column=col)
          
          # 円を描画
          x, y, r = 35, 35, 25
          canvas.create_oval(x - r, y - r, x + r, y + r, 
                             outline="blue", width=2)
          canvas.create_text(x, y, text=day, font=("Helvetica", 12))

          # ツールチップ（フォントサイズを小さく）
          tooltip = tk.Label(canvas, text=holidays[day], bg="yellow", 
                             font=("Helvetica", 7))  # サイズを1つ減少
          tooltip.place(x=5, y=50)

        else:
          label = tk.Label(self.calendar_frame, text=text, width=8, height=3, 
                           borderwidth=0)  # 枠線幅0
          label.grid(row=row, column=col)

  def update_calendar(self):
    """選択年月でカレンダーを更新"""
    year = self.year_var.get()
    month = self.month_var.get()
    self.display_calendar(year, month)


# アプリケーションの実行
if __name__ == "__main__":
  app = CalendarApp()
  app.mainloop()
