"""
Switch Downgrader — Automatic Dependencies Installer
"""
import os
import subprocess
import urllib.request
import tempfile
import threading
import tkinter as tk
from tkinter import ttk
from core.i18n import t

def check_dotnet8():
    """Returns True if .NET 8 (Core or Windows Desktop) is installed."""
    try:
        flags = 0
        if os.name == 'nt':
            flags = subprocess.CREATE_NO_WINDOW
        output = subprocess.check_output(['dotnet', '--list-runtimes'], text=True, creationflags=flags)
        return 'Microsoft.WindowsDesktop.App 8.0' in output or 'Microsoft.NETCore.App 8.0' in output
    except Exception:
        return False

def check_osfmount():
    """Returns True if OSFMount is found in Program Files."""
    paths = [
        r"C:\Program Files\OSFMount\OSFMount.com",
        r"C:\Program Files (x86)\OSFMount\OSFMount.com"
    ]
    return any(os.path.exists(p) for p in paths)

class DepsInstallerDialog(tk.Toplevel):
    """Dialog that downloads and installs missing dependencies silently."""
    def __init__(self, parent, missing_deps, on_complete):
        super().__init__(parent)
        self.transient(parent)
        self.title(t("deps.title"))
        self.configure(bg="#1a1b2e")
        self.geometry("420x160")
        self.resizable(False, False)
        self.missing_deps = missing_deps
        self.on_complete = on_complete
        self.success = False

        self.status_var = tk.StringVar(value=t("deps.starting"))
        
        tk.Label(self, textvariable=self.status_var, bg="#1a1b2e", fg="#e0e0e0", 
                 font=("Segoe UI", 10)).pack(pady=(25, 10))
                 
        self.progress = ttk.Progressbar(self, mode='determinate', length=340)
        self.progress.pack(pady=10)

        self.center_window()
        self.grab_set()
        self.protocol("WM_DELETE_WINDOW", lambda: None)  # Prevent closing
        
        threading.Thread(target=self._install_thread, daemon=True).start()

    def center_window(self):
        self.update_idletasks()
        w, h = self.winfo_width(), self.winfo_height()
        x = self.master.winfo_rootx() + (self.master.winfo_width() - w) // 2
        y = self.master.winfo_rooty() + (self.master.winfo_height() - h) // 2
        self.geometry(f"+{x}+{y}")

    def update_progress(self, block_num, block_size, total_size):
        if total_size > 0:
            percent = (block_num * block_size * 100) / total_size
            self.after(0, lambda: self.progress.config(value=min(percent, 100)))

    def _install_thread(self):
        temp_dir = tempfile.gettempdir()
        
        try:
            if "dotnet" in self.missing_deps:
                self.after(0, lambda: self.status_var.set(t("deps.downloading_dotnet")))
                url = "https://aka.ms/dotnet/8.0/windowsdesktop-runtime-win-x64.exe"
                installer_path = os.path.join(temp_dir, "dotnet8_installer.exe")
                urllib.request.urlretrieve(url, installer_path, self.update_progress)
                
                self.after(0, lambda: self.status_var.set(t("deps.installing_dotnet")))
                self.after(0, lambda: self.progress.config(mode='indeterminate'))
                self.after(0, self.progress.start)
                
                flags = 0
                if os.name == 'nt':
                    flags = subprocess.CREATE_NO_WINDOW
                subprocess.run([installer_path, '/install', '/quiet', '/norestart'], check=True, creationflags=flags)
                
                self.after(0, self.progress.stop)
                self.after(0, lambda: self.progress.config(mode='determinate', value=0))

            if "osfmount" in self.missing_deps:
                self.after(0, lambda: self.status_var.set(t("deps.downloading_osfmount")))
                url = "https://www.osforensics.com/downloads/osfmount.exe"
                installer_path = os.path.join(temp_dir, "osfmount_installer.exe")
                urllib.request.urlretrieve(url, installer_path, self.update_progress)
                
                self.after(0, lambda: self.status_var.set(t("deps.installing_osfmount")))
                self.after(0, lambda: self.progress.config(mode='indeterminate'))
                self.after(0, self.progress.start)
                
                subprocess.run([installer_path, '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART'], check=True)
                
                self.after(0, self.progress.stop)

            self.success = True
            self.after(0, lambda: self.status_var.set(t("deps.success")))
        except Exception as e:
            self.after(0, lambda: self.status_var.set(t("deps.error", error=str(e))))
            
            # Offer manual installation if automatic fails
            import webbrowser
            urls = []
            if "dotnet" in self.missing_deps:
                urls.append("https://dotnet.microsoft.com/en-us/download/dotnet/8.0/runtime")
            if "osfmount" in self.missing_deps:
                urls.append("https://www.osforensics.com/tools/mount-disk-images.html")
                
            if urls:
                def ask_manual():
                    from tkinter import messagebox
                    msg = t("deps.manual_fallback_msg")
                    if messagebox.askyesno(t("deps.manual_fallback_title"), msg, parent=self):
                        for url in urls:
                            webbrowser.open(url)
                self.after(500, ask_manual)
                
            import time
            time.sleep(3)
        finally:
            self.after(1000, self._finish)

    def _finish(self):
        self.destroy()
        if self.on_complete:
            self.on_complete(self.success)
