#!/usr/bin/env python3
"""Native Windows XP Run dialog (shell32.dll style) for Hyprland."""

import json
import os
import shlex
import subprocess
import sys
from pathlib import Path

os.environ.setdefault("DCONF_PROFILE", "/home/carsten/.config/hypr/dconf/profile")

import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
gi.require_version("GdkPixbuf", "2.0")
from gi.repository import Gtk, Gdk, GdkPixbuf

HISTORY_PATH = Path("/home/carsten/.local/share/xp-run/history.json")
RUN_ICON = "/usr/local/share/icons/luna/32x32/actions/system-run.png"
SOUND_SCRIPT = "/home/carsten/.config/hypr/scripts/xp-sound.sh"

XP_ALIASES = {
    "cmd": "ghostty",
    "cmd.exe": "ghostty",
    "explorer": "thunar",
    "explorer.exe": "thunar",
    "notepad": "mousepad",
    "notepad.exe": "mousepad",
    "control": "/home/carsten/.local/bin/xp-control-panel",
    "control.exe": "/home/carsten/.local/bin/xp-control-panel",
    "desk.cpl": "/home/carsten/.local/bin/xp-display-properties",
    "mmsys.cpl": "/home/carsten/.local/bin/xp-control-panel --sounds",
    "timedate.cpl": "/home/carsten/.local/bin/xp-calendar-popup",
    "taskmgr": "/home/carsten/.local/bin/xp-taskmgr",
    "taskmgr.exe": "/home/carsten/.local/bin/xp-taskmgr",
    "sndvol32": "pavucontrol",
    "sndvol32.exe": "pavucontrol",
    "mspaint": "swappy",
    "mspaint.exe": "swappy",
    "ssmaze": "/home/carsten/.local/bin/xp-screensaver --mode maze",
    "ssmaze.scr": "/home/carsten/.local/bin/xp-screensaver --mode maze",
}


def load_history():
    try:
        if HISTORY_PATH.exists():
            data = json.loads(HISTORY_PATH.read_text(encoding="utf-8"))
            if isinstance(data, list):
                return [str(x) for x in data[:25]]
    except Exception:
        pass
    return ["cmd", "control", "taskmgr", "desk.cpl", "thunar", "firefox"]


def save_history(cmd, hist):
    cleaned = [cmd] + [x for x in hist if x != cmd]
    HISTORY_PATH.parent.mkdir(parents=True, exist_ok=True)
    HISTORY_PATH.write_text(json.dumps(cleaned[:25], indent=2), encoding="utf-8")


class XPRunDialog(Gtk.Window):
    def __init__(self):
        super().__init__(title="Run")
        self.set_wmclass("xp-run", "xp-run")
        self.set_role("xp-run")
        self.set_resizable(False)
        self.set_default_size(368, 152)
        self.set_border_width(12)

        self.history = load_history()

        root = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        self.add(root)

        # Top row: 32x32 Run icon + classic XP description
        top = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        if os.path.exists(RUN_ICON):
            pb = GdkPixbuf.Pixbuf.new_from_file_at_scale(RUN_ICON, 32, 32, True)
            icon = Gtk.Image.new_from_pixbuf(pb)
        else:
            icon = Gtk.Image.new_from_icon_name("system-run", Gtk.IconSize.DND)
        icon.set_valign(Gtk.Align.START)
        top.pack_start(icon, False, False, 0)

        desc = Gtk.Label(
            label="Type the name of a program, folder, document, or\nInternet resource, and Windows will open it for you."
        )
        desc.set_xalign(0.0)
        desc.set_yalign(0.0)
        top.pack_start(desc, True, True, 0)
        root.pack_start(top, False, False, 0)

        # Middle row: "Open:" label + editable combobox with MRU history
        mid = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
        lbl = Gtk.Label.new_with_mnemonic("_Open:")
        lbl.set_xalign(0.0)
        mid.pack_start(lbl, False, False, 0)

        self.combo = Gtk.ComboBoxText.new_with_entry()
        for item in self.history:
            self.combo.append_text(item)
        self.entry = self.combo.get_child()
        self.entry.set_activates_default(True)
        if self.history:
            self.entry.set_text(self.history[0])
            self.entry.select_region(0, -1)
        lbl.set_mnemonic_widget(self.entry)
        mid.pack_start(self.combo, True, True, 0)
        root.pack_start(mid, False, False, 2)

        # Bottom row: OK / Cancel / Browse...
        btns = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
        btns.set_halign(Gtk.Align.END)

        ok_btn = Gtk.Button.new_with_label("OK")
        ok_btn.set_size_request(76, 24)
        ok_btn.set_can_default(True)
        ok_btn.connect("clicked", self.on_ok)
        btns.pack_start(ok_btn, False, False, 0)

        cancel_btn = Gtk.Button.new_with_label("Cancel")
        cancel_btn.set_size_request(76, 24)
        cancel_btn.connect("clicked", lambda *_: Gtk.main_quit())
        btns.pack_start(cancel_btn, False, False, 0)

        browse_btn = Gtk.Button.new_with_mnemonic("_Browse...")
        browse_btn.set_size_request(76, 24)
        browse_btn.connect("clicked", self.on_browse)
        btns.pack_start(browse_btn, False, False, 0)

        root.pack_end(btns, False, False, 0)
        self.set_default(ok_btn)

        self.connect("key-press-event", self.on_key)
        self.connect("destroy", Gtk.main_quit)

    def on_key(self, _w, ev):
        if ev.keyval == Gdk.KEY_Escape:
            Gtk.main_quit()
            return True
        return False

    def on_browse(self, _btn):
        dlg = Gtk.FileChooserDialog(
            title="Browse",
            parent=self,
            action=Gtk.FileChooserAction.OPEN,
            buttons=("Cancel", Gtk.ResponseType.CANCEL, "Open", Gtk.ResponseType.OK),
        )
        dlg.set_current_folder(str(Path.home()))
        if dlg.run() == Gtk.ResponseType.OK:
            path = dlg.get_filename()
            if path:
                self.entry.set_text(shlex.quote(path))
        dlg.destroy()

    def on_ok(self, _btn):
        raw = self.entry.get_text().strip()
        if not raw:
            return
        save_history(raw, self.history)
        low = raw.lower()
        expanded = os.path.expanduser(raw)

        if low in XP_ALIASES:
            cmd = XP_ALIASES[low]
        elif raw.startswith(("http://", "https://", "www.")):
            url = raw if raw.startswith("http") else f"https://{raw}"
            cmd = f"firefox {shlex.quote(url)}"
        elif os.path.isdir(expanded):
            cmd = f"thunar {shlex.quote(expanded)}"
        elif os.path.isfile(expanded) and not os.access(expanded, os.X_OK):
            cmd = f"xdg-open {shlex.quote(expanded)}"
        else:
            cmd = raw

        try:
            subprocess.Popen(["hyprctl", "dispatch", "exec", cmd],
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        except Exception as exc:
            subprocess.Popen([SOUND_SCRIPT, "error"],
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            err = Gtk.MessageDialog(
                transient_for=self,
                message_type=Gtk.MessageType.ERROR,
                buttons=Gtk.ButtonsType.OK,
                text=f"Windows cannot find '{raw}'.",
            )
            err.format_secondary_text(str(exc))
            err.run()
            err.destroy()
            return
        Gtk.main_quit()


def main():
    win = XPRunDialog()
    win.show_all()
    win.entry.grab_focus()
    Gtk.main()


if __name__ == "__main__":
    main()
