import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GLib

import socket
import json
import threading
import webbrowser

UDP_PORT = 9876

class UDPClient(Gtk.Window):
    def __init__(self):
        super().__init__(title="AI服务器发现工具")
        self.set_border_width(20)
        self.set_default_size(400, 150)

        self.label = Gtk.Label(label="监听中... 请确保 AI 服务器在线")
        self.add(self.label)

        self.popup_shown = False  # 每次启动只弹一次

        threading.Thread(target=self.listen_udp, daemon=True).start()

    def listen_udp(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.bind(("", UDP_PORT))
        print(f"Listening on UDP port {UDP_PORT}...")

        while True:
            data, addr = sock.recvfrom(1024)
            try:
                msg = json.loads(data.decode("utf-8"))
                if msg.get("type") == "ai_server_announce":
                    ip = msg.get("ip")
                    name = msg.get("name", "Unknown")
                    url = f"http://{ip}:80"  # 明确指定80端口

                    if not self.popup_shown:
                        self.popup_shown = True
                        GLib.idle_add(self.update_ui, name, url)

            except Exception as e:
                print("Error parsing message:", e)

    def update_ui(self, name, url):
        self.label.set_text(f"发现设备：{name}\n{url}")
        dialog = Gtk.MessageDialog(
            transient_for=self,
            flags=0,
            message_type=Gtk.MessageType.QUESTION,
            buttons=Gtk.ButtonsType.YES_NO,
            text="是否访问 AI 服务器？",
        )
        dialog.format_secondary_text(url)
        response = dialog.run()
        dialog.destroy()

        if response == Gtk.ResponseType.YES:
            webbrowser.open(url)

        return False

def main():
    app = UDPClient()
    app.connect("destroy", Gtk.main_quit)
    app.show_all()
    Gtk.main()

if __name__ == "__main__":
    main()

