#!/usr/bin/env python3
"""Native Windows XP Task Manager (Applications, Processes, Performance)."""

import collections
import json
import os
import pwd
import signal
import subprocess
import time
from pathlib import Path

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

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


def read_cpu_times():
    try:
        parts = Path("/proc/stat").read_text().splitlines()[0].split()[1:]
        vals = [int(x) for x in parts[:8]]
        idle = vals[3] + vals[4]
        total = sum(vals)
        return idle, total
    except Exception:
        return 0, 1


def read_meminfo():
    info = {}
    try:
        for line in Path("/proc/meminfo").read_text().splitlines():
            k, v = line.split(":", 1)
            info[k.strip()] = int(v.strip().split()[0])
    except Exception:
        pass
    return info


def read_processes(prev_proc_ticks, total_delta, ncpu):
    procs = []
    new_ticks = {}
    uid_cache = {}
    clk_tck = os.sysconf("SC_CLK_TCK")
    page_kb = os.sysconf("SC_PAGE_SIZE") // 1024

    for entry in os.scandir("/proc"):
        if not entry.name.isdigit():
            continue
        pid = int(entry.name)
        try:
            stat_txt = Path(f"/proc/{pid}/stat").read_text()
            rp = stat_txt.rfind(")")
            comm = stat_txt[stat_txt.find("(") + 1:rp]
            fields = stat_txt[rp + 2:].split()
            utime, stime = int(fields[11]), int(fields[12])
            rss_kb = int(fields[21]) * page_kb
            ticks = utime + stime
            new_ticks[pid] = ticks

            cpu_pct = 0.0
            if pid in prev_proc_ticks and total_delta > 0:
                cpu_pct = 100.0 * (ticks - prev_proc_ticks[pid]) * ncpu / float(total_delta)
                cpu_pct = max(0.0, min(99.9, cpu_pct))

            uid = os.stat(entry.path).st_uid
            if uid not in uid_cache:
                try:
                    uid_cache[uid] = pwd.getpwuid(uid).pw_name
                except KeyError:
                    uid_cache[uid] = str(uid)
            procs.append((comm, uid_cache[uid], int(round(cpu_pct)), rss_kb, pid))
        except Exception:
            continue
    procs.sort(key=lambda r: (r[2], r[3]), reverse=True)
    return procs, new_ticks


class XPGraph(Gtk.DrawingArea):
    """Iconic Windows XP Task Manager green-on-black oscilloscope graph."""

    def __init__(self, history_len=60):
        super().__init__()
        self.set_size_request(240, 86)
        self.values = collections.deque([0.0] * history_len, maxlen=history_len)
        self.grid_offset = 0
        self.connect("draw", self.on_draw)

    def push(self, pct):
        self.values.append(max(0.0, min(100.0, pct)))
        self.grid_offset = (self.grid_offset + 4) % 12
        self.queue_draw()

    def on_draw(self, _w, cr):
        a = self.get_allocation()
        w, h = a.width, a.height

        # Pitch black oscilloscope background
        cr.set_source_rgb(0.0, 0.0, 0.0)
        cr.rectangle(0, 0, w, h)
        cr.fill()

        # Classic #008040 dark-green 12x12 grid
        cr.set_source_rgb(0.0, 0.45, 0.22)
        cr.set_line_width(1.0)
        for x in range(w - self.grid_offset, 0, -12):
            cr.move_to(x + 0.5, 0)
            cr.line_to(x + 0.5, h)
        for y in range(12, h, 12):
            cr.move_to(0, y + 0.5)
            cr.line_to(w, y + 0.5)
        cr.stroke()

        # Bright #00FF00 trace
        n = len(self.values)
        if n > 1:
            cr.set_source_rgb(0.0, 1.0, 0.0)
            cr.set_line_width(1.3)
            for i, val in enumerate(self.values):
                x = (i / float(n - 1)) * (w - 2) + 1
                y = (h - 2) - (val / 100.0) * (h - 4)
                if i == 0:
                    cr.move_to(x, y)
                else:
                    cr.line_to(x, y)
            cr.stroke()

        # Sunken 1px inset border
        cr.set_source_rgb(0.5, 0.5, 0.5)
        cr.set_line_width(1.0)
        cr.rectangle(0.5, 0.5, w - 1, h - 1)
        cr.stroke()


class XPMeter(Gtk.DrawingArea):
    """Iconic Windows XP vertical LED bar meter."""

    def __init__(self):
        super().__init__()
        self.set_size_request(76, 86)
        self.pct = 0.0
        self.connect("draw", self.on_draw)

    def set_value(self, pct):
        self.pct = max(0.0, min(100.0, pct))
        self.queue_draw()

    def on_draw(self, _w, cr):
        a = self.get_allocation()
        w, h = a.width, a.height
        cr.set_source_rgb(0.0, 0.0, 0.0)
        cr.rectangle(0, 0, w, h)
        cr.fill()

        bar_top, bar_bot = 8, h - 22
        bar_h = max(10, bar_bot - bar_top)
        lit_y = bar_bot - int((self.pct / 100.0) * bar_h)

        # Dual green LED columns
        col_w = 14
        x1 = w // 2 - col_w - 2
        x2 = w // 2 + 2
        for y in range(bar_bot - 3, bar_top, -3):
            if y >= lit_y:
                cr.set_source_rgb(0.0, 1.0, 0.0)
            else:
                cr.set_source_rgb(0.0, 0.35, 0.16)
            cr.rectangle(x1, y, col_w, 2)
            cr.rectangle(x2, y, col_w, 2)
            cr.fill()

        # Percentage readout
        cr.set_source_rgb(0.0, 1.0, 0.0)
        cr.select_font_face("Tahoma", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
        cr.set_font_size(11)
        txt = f"{int(round(self.pct))}%"
        ext = cr.text_extents(txt)
        cr.move_to((w - ext.width) / 2.0, h - 7)
        cr.show_text(txt)

        cr.set_source_rgb(0.5, 0.5, 0.5)
        cr.set_line_width(1.0)
        cr.rectangle(0.5, 0.5, w - 1, h - 1)
        cr.stroke()


class XPTaskManager(Gtk.Window):
    def __init__(self):
        super().__init__(title="Windows Task Manager")
        self.set_wmclass("xp-taskmgr", "xp-taskmgr")
        self.set_default_size(450, 500)

        self.ncpu = os.cpu_count() or 1
        self.prev_idle, self.prev_total = read_cpu_times()
        self.prev_proc_ticks = {}

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

        # Menubar
        mb = Gtk.MenuBar()
        file_m = Gtk.MenuItem(label="File")
        fm = Gtk.Menu()
        mi_run = Gtk.MenuItem(label="New Task (Run...)")
        mi_run.connect("activate", lambda *_: subprocess.Popen(["/home/carsten/.local/bin/xp-run"]))
        mi_exit = Gtk.MenuItem(label="Exit Task Manager")
        mi_exit.connect("activate", lambda *_: Gtk.main_quit())
        fm.append(mi_run)
        fm.append(Gtk.SeparatorMenuItem())
        fm.append(mi_exit)
        file_m.set_submenu(fm)
        mb.append(file_m)

        view_m = Gtk.MenuItem(label="View")
        vm = Gtk.Menu()
        mi_ref = Gtk.MenuItem(label="Refresh Now")
        mi_ref.connect("activate", lambda *_: self.refresh())
        vm.append(mi_ref)
        view_m.set_submenu(vm)
        mb.append(view_m)
        root.pack_start(mb, False, False, 0)

        # Tabs
        self.nb = Gtk.Notebook()
        self.nb.set_border_width(6)
        root.pack_start(self.nb, True, True, 0)

        self._build_apps_tab()
        self._build_procs_tab()
        self._build_perf_tab()

        # Classic XP Statusbar
        sb = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        sb.set_border_width(4)
        self.sb_procs = Gtk.Label(label="Processes: 0", xalign=0)
        self.sb_cpu = Gtk.Label(label="CPU Usage: 0%", xalign=0)
        self.sb_mem = Gtk.Label(label="Commit Charge: 0M / 0M", xalign=0)
        sb.pack_start(self.sb_procs, False, False, 4)
        sb.pack_start(Gtk.Separator(orientation=Gtk.Orientation.VERTICAL), False, False, 0)
        sb.pack_start(self.sb_cpu, False, False, 4)
        sb.pack_start(Gtk.Separator(orientation=Gtk.Orientation.VERTICAL), False, False, 0)
        sb.pack_start(self.sb_mem, True, True, 4)
        root.pack_end(sb, False, False, 0)

        self.refresh()
        GLib.timeout_add(1000, self.refresh)
        self.connect("key-press-event", lambda _w, ev: Gtk.main_quit() if ev.keyval == Gdk.KEY_Escape else False)
        self.connect("destroy", Gtk.main_quit)

    def _build_apps_tab(self):
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
        box.set_border_width(8)

        sw = Gtk.ScrolledWindow()
        sw.set_shadow_type(Gtk.ShadowType.IN)
        self.apps_store = Gtk.ListStore(str, str, str)  # title, status, address
        self.apps_tv = Gtk.TreeView(model=self.apps_store)
        c1 = Gtk.TreeViewColumn("Task", Gtk.CellRendererText(), text=0)
        c1.set_expand(True)
        c2 = Gtk.TreeViewColumn("Status", Gtk.CellRendererText(), text=1)
        c2.set_min_width(80)
        self.apps_tv.append_column(c1)
        self.apps_tv.append_column(c2)
        sw.add(self.apps_tv)
        box.pack_start(sw, True, True, 0)

        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
        row.set_halign(Gtk.Align.END)
        for lbl, cb in [
            ("End Task", self._on_end_task),
            ("Switch To", self._on_switch_to),
            ("New Task...", lambda *_: subprocess.Popen(["/home/carsten/.local/bin/xp-run"])),
        ]:
            b = Gtk.Button.new_with_label(lbl)
            b.set_size_request(86, 24)
            b.connect("clicked", cb)
            row.pack_start(b, False, False, 0)
        box.pack_end(row, False, False, 0)
        self.nb.append_page(box, Gtk.Label(label="Applications"))

    def _build_procs_tab(self):
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
        box.set_border_width(8)

        sw = Gtk.ScrolledWindow()
        sw.set_shadow_type(Gtk.ShadowType.IN)
        self.procs_store = Gtk.ListStore(str, str, int, str, int, int)  # name, user, cpu, mem_str, mem_kb, pid
        self.procs_tv = Gtk.TreeView(model=self.procs_store)
        cols = [
            ("Image Name", 0, 0, True),
            ("User Name", 1, 1, False),
            ("CPU", 2, 2, False),
            ("Mem Usage", 3, 4, False),
            ("PID", 5, 5, False),
        ]
        for title, col_id, sort_id, expand in cols:
            r = Gtk.CellRendererText()
            if col_id in (2, 3, 5):
                r.set_property("xalign", 1.0)
            c = Gtk.TreeViewColumn(title, r, text=col_id)
            c.set_sort_column_id(sort_id)
            c.set_resizable(True)
            c.set_expand(expand)
            self.procs_tv.append_column(c)
        sw.add(self.procs_tv)
        box.pack_start(sw, True, True, 0)

        row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
        row.set_halign(Gtk.Align.END)
        end_b = Gtk.Button.new_with_label("End Process")
        end_b.set_size_request(96, 24)
        end_b.connect("clicked", self._on_end_proc)
        row.pack_start(end_b, False, False, 0)
        box.pack_end(row, False, False, 0)
        self.nb.append_page(box, Gtk.Label(label="Processes"))

    def _build_perf_tab(self):
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
        box.set_border_width(8)

        # Row 1: CPU Usage meter + CPU Usage History graph
        r1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
        f_cm = Gtk.Frame(label=" CPU Usage ")
        self.cpu_meter = XPMeter()
        self.cpu_meter.set_margin_top(4); self.cpu_meter.set_margin_bottom(6)
        self.cpu_meter.set_margin_start(6); self.cpu_meter.set_margin_end(6)
        f_cm.add(self.cpu_meter)
        r1.pack_start(f_cm, False, False, 0)

        f_cg = Gtk.Frame(label=" CPU Usage History ")
        self.cpu_graph = XPGraph()
        self.cpu_graph.set_margin_top(4); self.cpu_graph.set_margin_bottom(6)
        self.cpu_graph.set_margin_start(6); self.cpu_graph.set_margin_end(6)
        f_cg.add(self.cpu_graph)
        r1.pack_start(f_cg, True, True, 0)
        box.pack_start(r1, False, False, 0)

        # Row 2: Memory meter + Memory Usage History graph
        r2 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
        f_mm = Gtk.Frame(label=" Mem Usage ")
        self.mem_meter = XPMeter()
        self.mem_meter.set_margin_top(4); self.mem_meter.set_margin_bottom(6)
        self.mem_meter.set_margin_start(6); self.mem_meter.set_margin_end(6)
        f_mm.add(self.mem_meter)
        r2.pack_start(f_mm, False, False, 0)

        f_mg = Gtk.Frame(label=" Memory Usage History ")
        self.mem_graph = XPGraph()
        self.mem_graph.set_margin_top(4); self.mem_graph.set_margin_bottom(6)
        self.mem_graph.set_margin_start(6); self.mem_graph.set_margin_end(6)
        f_mg.add(self.mem_graph)
        r2.pack_start(f_mg, True, True, 0)
        box.pack_start(r2, False, False, 0)

        # Row 3: Classic stats frames (Physical Memory / Commit Charge)
        r3 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
        f_phys = Gtk.Frame(label=" Physical Memory (K) ")
        self.phys_lbl = Gtk.Label(label="", xalign=0)
        self.phys_lbl.set_margin_top(6); self.phys_lbl.set_margin_bottom(6)
        self.phys_lbl.set_margin_start(8); self.phys_lbl.set_margin_end(8)
        f_phys.add(self.phys_lbl)
        r3.pack_start(f_phys, True, True, 0)

        f_sys = Gtk.Frame(label=" Totals ")
        self.tot_lbl = Gtk.Label(label="", xalign=0)
        self.tot_lbl.set_margin_top(6); self.tot_lbl.set_margin_bottom(6)
        self.tot_lbl.set_margin_start(8); self.tot_lbl.set_margin_end(8)
        f_sys.add(self.tot_lbl)
        r3.pack_start(f_sys, True, True, 0)
        box.pack_start(r3, True, True, 0)

        self.nb.append_page(box, Gtk.Label(label="Performance"))

    def _on_end_task(self, _b):
        model, it = self.apps_tv.get_selection().get_selected()
        if it:
            addr = model[it][2]
            subprocess.Popen(["hyprctl", "dispatch", "closewindow", f"address:{addr}"],
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

    def _on_switch_to(self, _b):
        model, it = self.apps_tv.get_selection().get_selected()
        if it:
            addr = model[it][2]
            subprocess.Popen(["hyprctl", "dispatch", "focuswindow", f"address:{addr}"],
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

    def _on_end_proc(self, _b):
        model, it = self.procs_tv.get_selection().get_selected()
        if not it:
            return
        name, pid = model[it][0], model[it][5]
        dlg = Gtk.MessageDialog(
            transient_for=self,
            message_type=Gtk.MessageType.WARNING,
            buttons=Gtk.ButtonsType.YES_NO,
            text=f"Do you want to end the process '{name}' (PID {pid})?",
        )
        dlg.set_title("Task Manager Warning")
        dlg.format_secondary_text("Terminating a process can cause undesired results including loss of data.")
        resp = dlg.run()
        dlg.destroy()
        if resp == Gtk.ResponseType.YES:
            try:
                os.kill(pid, signal.SIGTERM)
            except OSError:
                pass
            self.refresh()

    def refresh(self):
        # 1. CPU & Memory
        idle, total = read_cpu_times()
        d_total = max(1, total - self.prev_total)
        d_idle = max(0, idle - self.prev_idle)
        cpu_pct = 100.0 * (1.0 - d_idle / float(d_total))
        self.prev_idle, self.prev_total = idle, total

        mi = read_meminfo()
        mem_tot = mi.get("MemTotal", 1)
        mem_avail = mi.get("MemAvailable", 0)
        mem_used = max(0, mem_tot - mem_avail)
        mem_pct = 100.0 * mem_used / float(mem_tot)
        cached = mi.get("Cached", 0)

        self.cpu_meter.set_value(cpu_pct)
        self.cpu_graph.push(cpu_pct)
        self.mem_meter.set_value(mem_pct)
        self.mem_graph.push(mem_pct)

        self.phys_lbl.set_text(
            f"Total:       {mem_tot:>10,}\n"
            f"Available:   {mem_avail:>10,}\n"
            f"System Cache:{cached:>10,}"
        )

        # 2. Applications (preserve selection)
        sel_addr = None
        m, it = self.apps_tv.get_selection().get_selected()
        if it:
            sel_addr = m[it][2]
        self.apps_store.clear()
        try:
            out = subprocess.check_output(["hyprctl", "clients", "-j"], text=True, timeout=1.0)
            for c in json.loads(out):
                if c.get("mapped", True) and c.get("title"):
                    it2 = self.apps_store.append([c["title"], "Running", c["address"]])
                    if c["address"] == sel_addr:
                        self.apps_tv.get_selection().select_iter(it2)
        except Exception:
            pass

        # 3. Processes (preserve selected PID)
        sel_pid = None
        m, it = self.procs_tv.get_selection().get_selected()
        if it:
            sel_pid = m[it][5]
        procs, self.prev_proc_ticks = read_processes(self.prev_proc_ticks, d_total, self.ncpu)
        self.procs_store.clear()
        for comm, user, cp, mem_kb, pid in procs[:140]:
            it2 = self.procs_store.append([comm, user, cp, f"{mem_kb:,} K", mem_kb, pid])
            if pid == sel_pid:
                self.procs_tv.get_selection().select_iter(it2)

        # 4. Totals & Statusbar
        uptime_s = 0
        try:
            uptime_s = int(float(Path("/proc/uptime").read_text().split()[0]))
        except Exception:
            pass
        hrs, rem = divmod(uptime_s, 3600)
        mins = rem // 60
        self.tot_lbl.set_text(
            f"Processes:   {len(procs):>8}\n"
            f"CPU Cores:   {self.ncpu:>8}\n"
            f"Up Time:     {hrs:>4}h {mins:02d}m"
        )
        self.sb_procs.set_text(f"Processes: {len(procs)}")
        self.sb_cpu.set_text(f"CPU Usage: {int(round(cpu_pct))}%")
        self.sb_mem.set_text(f"Commit Charge: {mem_used // 1024}M / {mem_tot // 1024}M")
        return True


def main():
    win = XPTaskManager()
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()
