import tkinter as tk
from tkinter import messagebox, ttk
import subprocess
import sys
import os
import threading

class VoshaInstaller:
    def __init__(self, root):
        self.root = root
        self.root.title("VOSHA Framework Installer v1.0")
        self.root.geometry("600x450")
        self.root.configure(bg="#eef2ff")
        self.root.resizable(False, False)

        # Style context
        self.primary_color = "#004aad"
        self.bg_color = "#eef2ff"
        self.text_color = "#101622"

        self.setup_ui()

    def setup_ui(self):
        # Header with Logo
        header_frame = tk.Frame(self.root, bg="white", height=80)
        header_frame.pack(fill="x")
        header_frame.pack_propagate(False)

        try:
            # Try to load logo (modern Tkinter supports PNG)
            logo_path = os.path.join(os.path.dirname(__file__), "vosha_framework", "logo.png")
            if not os.path.exists(logo_path):
                 logo_path = "logo.png" # Fallback
            
            temp_img = tk.PhotoImage(file=logo_path)
            # Scale down if too large (subsample)
            width = temp_img.width()
            height = temp_img.height()
            
            scale = 1
            if width > 100 or height > 100:
                scale = max(width // 60, height // 60)
            
            if scale > 1:
                self.logo_img = temp_img.subsample(scale, scale)
            else:
                self.logo_img = temp_img
                
            logo_label = tk.Label(header_frame, image=self.logo_img, bg="white")
            logo_label.pack(side="left", padx=20)
        except Exception as e:
            print(f"Could not load logo: {e}")

        tk.Label(header_frame, text="VOSHA", font=("Poppins", 18, "bold"), bg="white", fg=self.primary_color).pack(side="left")
        tk.Label(header_frame, text="Installer", font=("Poppins", 14), bg="white", fg="#636e72").pack(side="left", padx=5)

        # Content
        content_frame = tk.Frame(self.root, bg=self.bg_color, padx=40, pady=20)
        content_frame.pack(fill="both", expand=True)

        tk.Label(content_frame, text="Selamat Datang di VOSHA", font=("Poppins", 16, "bold"), bg=self.bg_color, fg=self.text_color).pack(anchor="w")
        tk.Label(content_frame, text="Menyiapkan sistem fullstack dalam hitungan detik.", font=("Poppins", 10), bg=self.bg_color, fg="#636e72").pack(anchor="w", pady=(0, 15))

        # Progress bar
        self.progress = ttk.Progressbar(content_frame, orient="horizontal", length=520, mode="determinate")
        self.progress.pack(pady=5)

        # Status Log
        tk.Label(content_frame, text="Status Instalasi:", font=("Poppins", 9, "bold"), bg=self.bg_color, fg=self.text_color).pack(anchor="w")
        self.log_text = tk.Text(content_frame, height=9, bg="#ffffff", font=("Courier New", 9), relief="flat", padx=10, pady=10)
        self.log_text.pack(fill="x", pady=(5, 15))
        self.log_text.insert("1.0", "Siap untuk memulai instalasi...\n")
        self.log_text.config(state="disabled")

        # Footer Buttons
        footer_frame = tk.Frame(self.root, bg=self.bg_color, pady=10)
        footer_frame.pack(fill="x")

        self.btn_install = tk.Button(footer_frame, text="Pasang VOSHA Sekarang", bg=self.primary_color, fg="white", 
                                font=("Poppins", 10, "bold"), padx=40, pady=10, relief="flat", cursor="hand2",
                                command=self.start_install)
        self.btn_install.pack()

    def update_log(self, message):
        self.log_text.config(state="normal")
        self.log_text.insert("end", f"> {message}\n")
        self.log_text.see("end")
        self.log_text.config(state="disabled")
        self.root.update_idletasks() # Force UI update

    def start_install(self):
        self.btn_install.config(state="disabled", text="Memasang...")
        self.progress["value"] = 10
        threading.Thread(target=self.run_installation, daemon=True).start()

    def run_installation(self):
        try:
            self.update_log("Mengecek lingkungan sistem...")
            is_linux = sys.platform.startswith("linux")
            
            # Use -m pip install . with flit/setuptools
            # Added --quiet to potentially speed up if output is the bottleneck
            cmd = [sys.executable, "-m", "pip", "install", ".", "--upgrade"]
            if is_linux:
                cmd.append("--break-system-packages")
            
            self.update_log("Memulai proses PIP (mohon tunggu)...")
            self.progress["value"] = 25
            
            # Using line buffering for real-time logs
            process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, 
                                     text=True, bufsize=1, universal_newlines=True,
                                     cwd=os.path.dirname(__file__))
            
            for line in process.stdout:
                line = line.strip()
                if line:
                    # Filter common progress lines to avoid log spam
                    if "Requirement already satisfied" in line:
                         self.update_log("Kebutuhan package terpenuhi...")
                         self.progress["value"] += 2
                    else:
                         self.update_log(line)
                         self.progress["value"] += 1
                    
                    if self.progress["value"] > 95: self.progress["value"] = 95

            process.wait()
            
            if process.returncode == 0:
                self.progress["value"] = 100
                self.update_log("CORE: VOSHA Framework rilis 1.0 berhasil dipasang!")
                self.update_log("-----------------------------------------")
                self.update_log("Silakan gunakan perintah 'vosha' di terminal.")
                messagebox.showinfo("Berhasil!", "VOSHA Framework v1.0 telah terpasang sempurna.\n\nSekarang Anda dapat menggunakan perintah 'vosha buat' di terminal.")
                self.btn_install.config(text="Selesai & Keluar", state="normal", command=self.root.quit)
            else:
                self.update_log("Gagal memasang package.")
                messagebox.showerror("Gagal", "Instalasi gagal. Silakan periksa log di layar.")
                self.btn_install.config(text="Coba Lagi", state="normal")
                
        except Exception as e:
            self.update_log(f"Kesalahan Sistem: {str(e)}")
            messagebox.showerror("Error", f"Terjadi kesalahan fatal: {str(e)}")
            self.btn_install.config(text="Coba Lagi", state="normal")

if __name__ == "__main__":
    root = tk.Tk()
    app = VoshaInstaller(root)
    root.mainloop()
