import socket
import json
import threading
import webbrowser
import tkinter as tk
from tkinter import messagebox

UDP_PORT = 9876
popup_shown = False  # 确保只弹一次

def open_browser(url):
    try:
        webbrowser.open(url)
    except Exception as e:
        print(f"Failed to open browser: {e}")

def listen_udp():
    global popup_shown

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(("", UDP_PORT))

    print(f"Listening for UDP broadcasts on port {UDP_PORT}...")

    while True:
        try:
            data, addr = sock.recvfrom(1024)
            print(f"Received raw data from {addr}: {data}")
            msg = json.loads(data.decode("utf-8"))

            if msg.get("type") == "ai_server_announce":
                ip = msg.get("ip")
                port = msg.get("port")
                name = msg.get("name", "Unknown")

                url = f"http://{ip}:80"
                print(f"Discovered {name} at {url}")

                if not popup_shown:
                    popup_shown = True

                    def show_popup():
                        if messagebox.askyesno("发现AI服务器", f"名称: {name}\n地址: {url}\n\n是否打开浏览器访问？"):
                            open_browser(url)

                    root.after(0, show_popup)

        except json.JSONDecodeError:
            print("Failed to decode JSON")
        except Exception as e:
            print(f"Error while receiving UDP: {e}")

# 初始化 Tkinter 主窗口（显示）
root = tk.Tk()
root.title("AI 服务器发现工具")
root.geometry("400x200")
label = tk.Label(root, text="正在监听 AI 服务器广播...\n端口: 9876", font=("Arial", 12))
label.pack(pady=60)

# 启动监听线程
listener_thread = threading.Thread(target=listen_udp, daemon=True)
listener_thread.start()

# 启动 UI 主循环
root.mainloop()
