import requests
import json
from datetime import datetime
import tkinter as tk
from tkinter import messagebox, scrolledtext
import webbrowser

def validate_numeric_date_input(date_str):
    if not date_str.isdigit():
        messagebox.showerror('輸入錯誤', '日期只能是數字!')
        return False
    if len(date_str) != 8:
        messagebox.showerror('輸入錯誤', '日期長度有誤!')
        return False
    try:
        valid_date = datetime.strptime(date_str, '%Y%m%d')
        return valid_date
    except ValueError:
        messagebox.showerror('輸入錯誤', '日期格式有誤!')
        return False

def fetch_google_trend(datestr):
    url = f'https://trends.google.com.tw/trends/api/dailytrends?hl=zh-TW&tz=-480&ed={datestr}&geo=TW&hl=zh-TW&ns=15'
    
    try:
        resp = requests.get(url)
        resp.raise_for_status()
    except requests.RequestException as e:
        messagebox.showerror('請求錯誤', f'請求失敗: {e}')
        return None

    try:
        searches = json.loads(resp.text.replace(')]}\',', ''))
        trending_searches = searches['default']['trendingSearchesDays'][0]['trendingSearches']
        if not trending_searches:
            messagebox.showerror('資料錯誤', '無法取得趨勢資料')
            return None
        return trending_searches
    except (json.JSONDecodeError, KeyError, IndexError) as e:
        messagebox.showerror('無法取得趨勢資料', f'日期過久: {e}')
        return None

def display_trends(trending_searches):
    trend_display.delete(1.0, tk.END)
    for result in trending_searches:
        trend_display.insert(tk.END, f'【{result["title"]["query"]}:{result["formattedTraffic"]}】\n', 'bold')
        for idx, article in enumerate(result['articles'], start=1):
            trend_display.insert(tk.END, f'{idx:0>2}. {article["title"]} ', 'normal')
            trend_display.insert(tk.END, f'{article["url"]}\n', ('link', article["url"]))
        trend_display.insert(tk.END, '\n')

def search_trends():
    datestr = entry_date.get()
    result = validate_numeric_date_input(datestr)
    if result:
        trending_searches = fetch_google_trend(datestr)
        if trending_searches:
            display_trends(trending_searches)

def open_link(event):
    current_index = trend_display.index(tk.CURRENT)
    line_start = current_index.split('.')[0]
    line_text = trend_display.get(f'{line_start}.0', f'{line_start}.end')
    
    possible_url = line_text.split()[-1]
    if possible_url.startswith('http'):
        webbrowser.open(possible_url)
    else:
        messagebox.showinfo('無效操作', '此行不包含有效的連結')

def on_enter_link(event):
    trend_display.config(cursor='hand2')

def on_leave_link(event):
    trend_display.config(cursor='')

root = tk.Tk()
root.title('Google搜尋趨勢查詢')

root.geometry('1024x786')

frame = tk.Frame(root)
frame.pack(pady=5)

label_date = tk.Label(frame, text='請輸入查詢Google搜尋趨勢的日期(YYYYMMDD)', font=('Microsoft JhengHei', 14))
label_date.grid(row=0, column=0, padx=5)
           
entry_date = tk.Entry(frame, width=10, font=('Microsoft JhengHei', 14))
entry_date.grid(row=0, column=1, padx=5)

btn_search = tk.Button(frame, text='查詢', command=search_trends, font=('Microsoft JhengHei', 14))
btn_search.grid(row=0, column=2, padx=5)

trend_display = scrolledtext.ScrolledText(root, width=1024, height=786)
trend_display.pack(pady=10)

trend_display.tag_configure('bold', font=('Microsoft JhengHei', 14, 'bold'))
trend_display.tag_configure('normal', font=('Microsoft JhengHei', 14))
trend_display.tag_configure('link', foreground='blue', underline=True, font=('Arial', 14))

trend_display.tag_bind('link', '<Button-1>', open_link)
trend_display.tag_bind('link', '<Enter>', on_enter_link)
trend_display.tag_bind('link', '<Leave>', on_leave_link)

root.mainloop()