import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import subprocess
import os
import sys
import threading
import json
import time

class GoBuilderGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("Go 代码打包器 v2.0 - 支持图标嵌入")
        self.root.geometry("800x620")
        self.root.resizable(False, False)
        
        # 变量
        self.source_dir = tk.StringVar()
        self.output_dir = tk.StringVar()
        self.app_name = tk.StringVar(value="myapp")
        self.app_icon = tk.StringVar()
        self.goos = tk.StringVar(value="windows")
        self.goarch = tk.StringVar(value="amd64")
        self.hide_console = tk.BooleanVar(value=False)
        self.build_status = tk.StringVar(value="就绪")
        self.embed_icon_method = tk.StringVar(value="go-winres")
        
        # 创建界面
        self.create_widgets()
        
        # 默认输出目录
        self.output_dir.set(os.path.join(os.getcwd(), "dist"))
        
    def create_widgets(self):
        # 主框架
        main_frame = ttk.Frame(self.root, padding="15")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # ========== 标题 ==========
        title_label = ttk.Label(main_frame, text="🚀 Go 代码打包工具", font=("Arial", 16, "bold"))
        title_label.grid(row=0, column=0, columnspan=3, sticky="w", pady=(0, 15))
        
        # ========== 源目录 ==========
        ttk.Label(main_frame, text="📂 Go 源码目录：", font=("Arial", 10, "bold")).grid(row=1, column=0, sticky="w", pady=(0, 5))
        
        src_frame = ttk.Frame(main_frame)
        src_frame.grid(row=2, column=0, columnspan=3, sticky="ew", pady=(0, 10))
        self.source_entry = ttk.Entry(src_frame, textvariable=self.source_dir, width=60)
        self.source_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
        ttk.Button(src_frame, text="浏览...", command=self.browse_source, width=10).pack(side=tk.RIGHT)
        
        # ========== 输出目录 ==========
        ttk.Label(main_frame, text="📁 输出目录：", font=("Arial", 10, "bold")).grid(row=3, column=0, sticky="w", pady=(0, 5))
        
        out_frame = ttk.Frame(main_frame)
        out_frame.grid(row=4, column=0, columnspan=3, sticky="ew", pady=(0, 10))
        self.output_entry = ttk.Entry(out_frame, textvariable=self.output_dir, width=60)
        self.output_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
        ttk.Button(out_frame, text="浏览...", command=self.browse_output, width=10).pack(side=tk.RIGHT)
        
        # ========== 应用名称 ==========
        ttk.Label(main_frame, text="🏷️ 应用名称：", font=("Arial", 10, "bold")).grid(row=5, column=0, sticky="w", pady=(0, 5))
        name_frame = ttk.Frame(main_frame)
        name_frame.grid(row=6, column=0, columnspan=3, sticky="w", pady=(0, 10))
        self.name_entry = ttk.Entry(name_frame, textvariable=self.app_name, width=30)
        self.name_entry.pack(side=tk.LEFT)
        ttk.Label(name_frame, text="（不需要加 .exe 后缀）", font=("Arial", 9), foreground="gray").pack(side=tk.LEFT, padx=(10, 0))
        
        # ========== 图标选择 ==========
        ttk.Label(main_frame, text="🖼️ 应用图标（.ico）：", font=("Arial", 10, "bold")).grid(row=7, column=0, sticky="w", pady=(0, 5))
        
        icon_frame = ttk.Frame(main_frame)
        icon_frame.grid(row=8, column=0, columnspan=3, sticky="ew", pady=(0, 10))
        self.icon_entry = ttk.Entry(icon_frame, textvariable=self.app_icon, width=50)
        self.icon_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
        ttk.Button(icon_frame, text="选择图标", command=self.browse_icon, width=10).pack(side=tk.RIGHT)
        
        # ========== 构建选项 ==========
        options_frame = ttk.LabelFrame(main_frame, text="构建选项", padding="10")
        options_frame.grid(row=9, column=0, columnspan=3, sticky="ew", pady=(0, 10))
        
        # 第一行：系统和架构
        row1 = ttk.Frame(options_frame)
        row1.pack(fill=tk.X, pady=(0, 8))
        
        ttk.Label(row1, text="目标系统：").pack(side=tk.LEFT, padx=(0, 8))
        os_combo = ttk.Combobox(row1, textvariable=self.goos, values=["windows", "linux", "darwin"], width=12, state="readonly")
        os_combo.pack(side=tk.LEFT, padx=(0, 20))
        
        ttk.Label(row1, text="架构：").pack(side=tk.LEFT, padx=(0, 8))
        arch_combo = ttk.Combobox(row1, textvariable=self.goarch, values=["amd64", "386", "arm64", "arm"], width=12, state="readonly")
        arch_combo.pack(side=tk.LEFT)
        
        # 第二行：选项
        row2 = ttk.Frame(options_frame)
        row2.pack(fill=tk.X, pady=(0, 8))
        
        ttk.Checkbutton(row2, text="隐藏控制台窗口（GUI程序）", variable=self.hide_console).pack(side=tk.LEFT)
        
        # 第三行：图标嵌入方式
        row3 = ttk.Frame(options_frame)
        row3.pack(fill=tk.X)
        
        ttk.Label(row3, text="图标嵌入：").pack(side=tk.LEFT, padx=(0, 8))
        ttk.Radiobutton(row3, text="go-winres（推荐）", variable=self.embed_icon_method, value="go-winres").pack(side=tk.LEFT, padx=(0, 15))
        ttk.Radiobutton(row3, text="rsrc", variable=self.embed_icon_method, value="rsrc").pack(side=tk.LEFT)
        
        # ========== 按钮区域 ==========
        btn_frame = ttk.Frame(main_frame)
        btn_frame.grid(row=10, column=0, columnspan=3, sticky="ew", pady=(10, 0))
        
        self.build_btn = ttk.Button(btn_frame, text="🚀 开始打包", command=self.start_build, width=18)
        self.build_btn.pack(side=tk.LEFT, padx=(0, 15))
        
        ttk.Button(btn_frame, text="📂 打开输出目录", command=self.open_output_dir, width=15).pack(side=tk.LEFT, padx=(0, 15))
        ttk.Button(btn_frame, text="🧹 清空日志", command=self.clear_log, width=12).pack(side=tk.LEFT)
        
        # ========== 状态栏 ==========
        status_frame = ttk.Frame(main_frame)
        status_frame.grid(row=11, column=0, columnspan=3, sticky="ew", pady=(12, 0))
        
        ttk.Separator(status_frame, orient='horizontal').pack(fill=tk.X, pady=(0, 8))
        
        status_label = ttk.Label(status_frame, textvariable=self.build_status, font=("Arial", 9, "bold"))
        status_label.pack(side=tk.LEFT)
        
        # ========== 日志输出框 ==========
        log_frame = ttk.LabelFrame(main_frame, text="📋 构建日志", padding="5")
        log_frame.grid(row=12, column=0, columnspan=3, sticky="nsew", pady=(8, 0))
        
        # 创建文本区域和滚动条
        text_container = ttk.Frame(log_frame)
        text_container.pack(fill=tk.BOTH, expand=True)
        
        self.log_text = tk.Text(
            text_container, 
            height=10, 
            font=("Consolas", 9), 
            wrap=tk.WORD,
            bg="#f5f5f5",
            fg="#333333"
        )
        self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        scrollbar = ttk.Scrollbar(text_container, orient=tk.VERTICAL, command=self.log_text.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.log_text.config(yscrollcommand=scrollbar.set)
        
        # 配置网格权重
        main_frame.columnconfigure(0, weight=1)
        main_frame.rowconfigure(12, weight=1)
        
        # 添加初始提示
        self.log_text.insert(tk.END, "💡 选择源码目录后点击「开始打包」\n")
        self.log_text.insert(tk.END, "📌 支持 Windows/Linux/macOS 交叉编译\n")
        self.log_text.insert(tk.END, "🎨 选择 .ico 文件可嵌入应用图标\n")
        self.log_text.see(tk.END)
        
    def browse_source(self):
        directory = filedialog.askdirectory(title="选择 Go 源码目录（包含 main.go）")
        if directory:
            self.source_dir.set(directory)
            dir_name = os.path.basename(directory)
            if dir_name and (not self.app_name.get() or self.app_name.get() == "myapp"):
                self.app_name.set(dir_name)
            self.log_message(f"✅ 已选择源码目录：{directory}")
            
    def browse_output(self):
        directory = filedialog.askdirectory(title="选择输出目录")
        if directory:
            self.output_dir.set(directory)
            self.log_message(f"✅ 已选择输出目录：{directory}")
            
    def browse_icon(self):
        file_path = filedialog.askopenfilename(
            title="选择图标文件（.ico）",
            filetypes=[("图标文件", "*.ico"), ("所有文件", "*.*")]
        )
        if file_path:
            self.app_icon.set(file_path)
            self.log_message(f"✅ 已选择图标：{os.path.basename(file_path)}")
            
    def open_output_dir(self):
        output_path = self.output_dir.get()
        if os.path.exists(output_path):
            if sys.platform == "win32":
                os.startfile(output_path)
            elif sys.platform == "darwin":
                subprocess.run(["open", output_path])
            else:
                subprocess.run(["xdg-open", output_path])
        else:
            messagebox.showwarning("提示", "输出目录不存在")
            
    def clear_log(self):
        """清空日志"""
        self.log_text.delete(1.0, tk.END)
        self.build_status.set("就绪")
        self.log_message("🧹 日志已清空")
        
    def log_message(self, message):
        """添加日志到文本框 - 线程安全"""
        def _log():
            self.log_text.insert(tk.END, message + "\n")
            self.log_text.see(tk.END)
            self.root.update_idletasks()
        
        # 如果当前在非UI线程，使用 after 方法
        if threading.current_thread() is threading.main_thread():
            _log()
        else:
            self.root.after(0, _log)
            
    def check_tool_installed(self, tool_name):
        """检查工具是否已安装"""
        try:
            # 使用 which 或 where 命令检查
            if sys.platform == "win32":
                check_cmd = ["where", tool_name]
            else:
                check_cmd = ["which", tool_name]
                
            result = subprocess.run(
                check_cmd,
                capture_output=True,
                text=True,
                timeout=2
            )
            
            if result.returncode == 0:
                return True
                
            # 如果 which/where 失败，尝试直接运行
            test_cmd = [tool_name, "--version"] if tool_name == "go-winres" else [tool_name, "--help"]
            result = subprocess.run(
                test_cmd,
                capture_output=True,
                text=True,
                timeout=2
            )
            return result.returncode == 0
            
        except (subprocess.TimeoutExpired, FileNotFoundError):
            return False
            
    def install_tool(self, tool_name):
        """安装工具"""
        self.log_message(f"📦 正在安装 {tool_name}...")
        self.build_status.set(f"正在安装 {tool_name}...")
        
        try:
            if tool_name == "go-winres":
                cmd = ["go", "install", "github.com/tc-hib/go-winres@latest"]
            else:
                cmd = ["go", "install", "github.com/akavel/rsrc@latest"]
                
            self.log_message(f"执行：{' '.join(cmd)}")
            
            process = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                encoding='utf-8',
                errors='replace'
            )
            
            # 实时输出安装日志
            for line in process.stdout:
                if line.strip():
                    self.log_message(f"  {line.strip()}")
                    
            process.wait()
            
            if process.returncode == 0:
                self.log_message(f"✅ {tool_name} 安装成功！")
                self.build_status.set(f"{tool_name} 已安装")
                messagebox.showinfo("成功", f"{tool_name} 安装成功！\n\n请重新点击「开始打包」")
                return True
            else:
                error_msg = process.stderr.read()
                self.log_message(f"❌ 安装失败：{error_msg}")
                self.build_status.set("安装失败")
                return False
                
        except Exception as e:
            self.log_message(f"❌ 安装异常：{str(e)}")
            return False
            
    def start_build(self):
        """开始构建"""
        # 检查源码目录
        source = self.source_dir.get().strip()
        if not source:
            messagebox.showerror("错误", "请选择 Go 源码目录")
            return
            
        if not os.path.exists(source):
            messagebox.showerror("错误", "源码目录不存在")
            return
            
        # 检查输出目录
        output = self.output_dir.get().strip()
        if not output:
            messagebox.showerror("错误", "请设置输出目录")
            return
            
        # 创建输出目录
        os.makedirs(output, exist_ok=True)
        
        # 检查图标嵌入工具
        icon_path = self.app_icon.get()
        if icon_path and os.path.exists(icon_path) and self.goos.get() == "windows":
            method = self.embed_icon_method.get()
            tool_installed = self.check_tool_installed(method)
            
            if not tool_installed:
                reply = messagebox.askyesno(
                    "工具未安装",
                    f"{method} 未安装，是否自动安装？\n\n"
                    f"安装命令：go install github.com/tc-hib/go-winres@latest"
                    if method == "go-winres" else
                    f"安装命令：go install github.com/akavel/rsrc@latest"
                )
                if reply:
                    self.install_tool(method)
                    # 安装后重新检查
                    if not self.check_tool_installed(method):
                        messagebox.showwarning("提示", "安装失败，图标将不会被嵌入")
                else:
                    messagebox.showwarning("提示", "将跳过图标嵌入")
        
        # 禁用按钮
        self.build_btn.config(state=tk.DISABLED, text="⏳ 打包中...")
        self.build_status.set("正在打包...")
        self.clear_log()
        self.log_message("=" * 60)
        self.log_message("🚀 开始构建流程...")
        
        # 在新线程中执行构建
        thread = threading.Thread(target=self.build_go, args=(source, output), daemon=True)
        thread.start()
        
    def embed_icon_winres(self, source_dir, icon_path):
        """使用 go-winres 嵌入图标"""
        try:
            self.log_message("🎨 使用 go-winres 嵌入图标...")
            
            app_name = self.app_name.get().strip() or "myapp"
            
            # 创建 winres.json 配置
            config = {
                "RT_GROUP_ICON": {
                    "MAINICON": {
                        "IDs": [1],
                        "Files": [icon_path]
                    }
                },
                "RT_VERSION": {
                    "1": {
                        "FixedFileInfo": {
                            "FileVersion": "1.0.0.0",
                            "ProductVersion": "1.0.0.0"
                        },
                        "StringFileInfo": {
                            "040904B0": {
                                "CompanyName": "",
                                "FileDescription": app_name,
                                "FileVersion": "1.0.0",
                                "InternalName": app_name,
                                "OriginalFilename": app_name + ".exe",
                                "ProductName": app_name,
                                "ProductVersion": "1.0.0"
                            }
                        }
                    }
                }
            }
            
            config_path = os.path.join(source_dir, "winres.json")
            with open(config_path, "w", encoding="utf-8") as f:
                json.dump(config, f, indent=2, ensure_ascii=False)
            
            self.log_message(f"📄 配置文件：{config_path}")
            
            # 执行 go-winres
            cmd = ["go-winres", "make", "--in", config_path]
            self.log_message(f"执行：{' '.join(cmd)}")
            
            result = subprocess.run(
                cmd,
                cwd=source_dir,
                capture_output=True,
                text=True,
                encoding='utf-8',
                errors='replace'
            )
            
            # 清理配置文件
            if os.path.exists(config_path):
                os.remove(config_path)
                
            if result.returncode == 0:
                # 检查是否生成了资源文件
                syso_files = [f for f in os.listdir(source_dir) if f.endswith('.syso')]
                if syso_files:
                    self.log_message(f"✅ 已生成资源文件：{', '.join(syso_files)}")
                    return True
                else:
                    self.log_message("⚠️ 未生成 .syso 文件")
                    return False
            else:
                self.log_message(f"❌ go-winres 失败：{result.stderr}")
                return False
                
        except Exception as e:
            self.log_message(f"❌ go-winres 异常：{str(e)}")
            return False
            
    def embed_icon_rsrc(self, source_dir, icon_path):
        """使用 rsrc 嵌入图标"""
        try:
            self.log_message("🎨 使用 rsrc 嵌入图标...")
            
            cmd = ["rsrc", "-ico", icon_path, "-o", "rsrc.syso"]
            self.log_message(f"执行：{' '.join(cmd)}")
            
            result = subprocess.run(
                cmd,
                cwd=source_dir,
                capture_output=True,
                text=True,
                encoding='utf-8',
                errors='replace'
            )
            
            if result.returncode == 0:
                syso_path = os.path.join(source_dir, "rsrc.syso")
                if os.path.exists(syso_path):
                    self.log_message(f"✅ 已生成资源文件：rsrc.syso")
                    return True
                else:
                    self.log_message("⚠️ 未生成 rsrc.syso 文件")
                    return False
            else:
                self.log_message(f"❌ rsrc 失败：{result.stderr}")
                return False
                
        except Exception as e:
            self.log_message(f"❌ rsrc 异常：{str(e)}")
            return False
            
    def build_go(self, source_dir, output_dir):
        """执行 Go 构建"""
        try:
            app_name = self.app_name.get().strip() or "myapp"
            output_path = os.path.join(output_dir, app_name)
            
            # Windows 添加 .exe 后缀
            if self.goos.get() == "windows" and not output_path.endswith('.exe'):
                output_path += '.exe'
                
            self.log_message("=" * 60)
            self.log_message(f"📦 应用名称：{app_name}")
            self.log_message(f"📂 源码目录：{source_dir}")
            self.log_message(f"📁 输出目录：{output_dir}")
            self.log_message(f"🖥️  目标平台：{self.goos.get()}/{self.goarch.get()}")
            self.log_message("=" * 60)
            
            # ========== 嵌入图标 ==========
            icon_embedded = False
            icon_path = self.app_icon.get()
            
            if icon_path and os.path.exists(icon_path) and self.goos.get() == "windows":
                method = self.embed_icon_method.get()
                self.log_message(f"🎨 尝试使用 {method} 嵌入图标...")
                
                if method == "go-winres":
                    icon_embedded = self.embed_icon_winres(source_dir, icon_path)
                else:
                    icon_embedded = self.embed_icon_rsrc(source_dir, icon_path)
                    
                if icon_embedded:
                    self.log_message("✅ 图标资源准备完成")
                else:
                    self.log_message("⚠️ 图标嵌入失败，继续编译...")
            else:
                if not icon_path:
                    self.log_message("ℹ️ 未选择图标")
                elif self.goos.get() != "windows":
                    self.log_message("ℹ️ 非 Windows 平台，跳过图标嵌入")
            
            # ========== 构建命令 ==========
            cmd = ["go", "build"]
            
            # 添加 ldflags
            ldflags = []
            if self.goos.get() == "windows" and self.hide_console.get():
                ldflags.extend(["-H", "windowsgui"])
                self.log_message("🔧 启用隐藏控制台模式")
                
            if ldflags:
                cmd.extend(["-ldflags", " ".join(ldflags)])
                
            cmd.extend(["-o", output_path])
            cmd.append(".")
            
            self.log_message(f"🔨 执行命令：{' '.join(cmd)}")
            self.log_message("⏳ 正在编译，请稍候...")
            
            # 设置环境变量
            env = os.environ.copy()
            env["GOOS"] = self.goos.get()
            env["GOARCH"] = self.goarch.get()
            env["CGO_ENABLED"] = "0"
            
            # 执行构建
            process = subprocess.Popen(
                cmd,
                cwd=source_dir,
                env=env,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                encoding='utf-8',
                errors='replace',
                bufsize=1
            )
            
            # 实时读取输出
            while True:
                stdout_line = process.stdout.readline()
                stderr_line = process.stderr.readline()
                
                if stdout_line:
                    line = stdout_line.strip()
                    if line:
                        self.log_message(f"  {line}")
                        
                if stderr_line:
                    line = stderr_line.strip()
                    if line:
                        self.log_message(f"  ⚠️ {line}")
                        
                if not stdout_line and not stderr_line and process.poll() is not None:
                    break
            
            # 等待进程结束
            process.wait()
            
            # 清理临时文件
            syso_files = [f for f in os.listdir(source_dir) if f.endswith('.syso')]
            for syso_file in syso_files:
                file_path = os.path.join(source_dir, syso_file)
                try:
                    os.remove(file_path)
                    self.log_message(f"🧹 清理临时文件：{syso_file}")
                except:
                    pass
                    
            # 清理 winres.json
            json_file = os.path.join(source_dir, "winres.json")
            if os.path.exists(json_file):
                try:
                    os.remove(json_file)
                except:
                    pass
            
            # 检查结果
            self.log_message("=" * 60)
            if process.returncode == 0:
                self.log_message("✅ 打包成功！🎉")
                self.log_message(f"📁 文件位置：{output_path}")
                
                if os.path.exists(output_path):
                    size = os.path.getsize(output_path) / (1024 * 1024)
                    self.log_message(f"📊 文件大小：{size:.2f} MB")
                    
                if icon_embedded:
                    self.log_message("✅ 图标已嵌入到 exe 文件中")
                else:
                    self.log_message("ℹ️ 程序未包含自定义图标")
                    
                self.build_status.set("✅ 打包完成")
                
                self.root.after(0, lambda: messagebox.showinfo(
                    "成功", 
                    f"打包完成！\n\n📁 文件保存在：{output_path}"
                ))
            else:
                self.log_message("❌ 打包失败！")
                self.build_status.set("❌ 打包失败")
                
                self.root.after(0, lambda: messagebox.showerror(
                    "错误", 
                    "打包失败，请查看日志详情"
                ))
                
        except FileNotFoundError:
            self.log_message("❌ 错误：未找到 Go 编译器")
            self.log_message("请安装 Go：https://golang.org/dl/")
            self.build_status.set("❌ 未找到 Go")
            
        except Exception as e:
            self.log_message(f"❌ 异常错误：{str(e)}")
            self.build_status.set("❌ 发生错误")
            
        finally:
            self.root.after(0, self.reset_build_button)
            
    def reset_build_button(self):
        """恢复构建按钮"""
        self.build_btn.config(state=tk.NORMAL, text="🚀 开始打包")
        
if __name__ == "__main__":
    root = tk.Tk()
    app = GoBuilderGUI(root)
    root.mainloop()