#!/usr/bin/env python3
"""mux dashboard — interactive visual overview of all desks and windows."""

import subprocess, os, sys, time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from muxlib import load_json, relative_time, run_stdout, notes_count as mux_notes_count, worktree_slugs as mux_worktree_slugs, load_projects as mux_load_projects


def main():
    projects = mux_load_projects()
    current = run_stdout("tmux display-message -p '#{session_name}'")
    now = int(time.time())

    sessions_raw = run_stdout("tmux list-sessions -F '#{session_name}|#{session_activity}'")
    sessions = {}
    if sessions_raw:
        for line in sessions_raw.split("\n"):
            parts = line.split("|")
            sessions[parts[0]] = int(parts[1]) if len(parts) > 1 else now

    windows_raw = run_stdout("tmux list-windows -a -F '#{session_name}|#{window_index}|#{window_name}|#{window_active}|#{window_activity}|#{pane_current_command}'")

    desk_windows = {}
    if windows_raw:
        for line in windows_raw.split("\n"):
            if not line:
                continue
            parts = line.split("|")
            if len(parts) < 3:
                continue
            sess = parts[0]
            desk_windows.setdefault(sess, []).append({
                "idx": parts[1] if len(parts) > 1 else "?",
                "name": parts[2] if len(parts) > 2 else "?",
                "active": parts[3] == "1" if len(parts) > 3 else False,
                "activity": int(parts[4]) if len(parts) > 4 and parts[4].isdigit() else now,
                "cmd": parts[5] if len(parts) > 5 else "?"
            })

    # Build selectable items for fzf
    items = []
    for sess_name in sorted(sessions.keys()):
        is_current = sess_name == current
        marker = "▶" if is_current else " "
        nc = int(mux_notes_count(sess_name))
        notes_str = f" [{nc} note{'s' if nc != 1 else ''}]" if nc > 0 else ""
        wt_slugs = mux_worktree_slugs(sess_name)

        # Desk header line
        desk_label = f"{marker} {sess_name}{notes_str}"
        first_win = desk_windows.get(sess_name, [{}])[0].get("idx", "1")
        items.append(f"{sess_name}:{first_win}|{desk_label}")

        for w in desk_windows.get(sess_name, []):
            age = now - w["activity"]
            from datetime import datetime, timezone
            activity_iso = datetime.fromtimestamp(w["activity"]).isoformat()
            age_str = relative_time(activity_iso)

            is_shell = w["cmd"] in ("zsh", "bash", "sh", "fish", "login")
            claude_icon = " ⚡" if not is_shell else ""
            wt_icon = " (wt)" if w["name"] in wt_slugs else ""
            active_dot = "●" if w["active"] else " "

            display = f"      {active_dot} {w['idx']}:{w['name']}{claude_icon}{wt_icon}  {age_str}"
            items.append(f"{sess_name}:{w['idx']}|{display}")

    # Add parked desks
    for p in sorted(projects.keys()):
        if p not in sessions:
            items.append(f"{p}:new|  {p}  (parked — Enter to open)")

    if not items:
        print("No desks configured.")
        return

    # Pipe through fzf
    header = "mux dashboard — ↑↓ navigate, Enter to switch, Esc to close"
    fzf_input = "\n".join(items)

    try:
        result = subprocess.run(
            ["fzf", "--ansi", "--no-sort", "--reverse",
             "--header", header,
             "--delimiter", "\\|",
             "--with-nth", "2",
             "--height", "100%",
             "--prompt", "switch> "],
            input=fzf_input, capture_output=True, text=True
        )
    except FileNotFoundError:
        print("fzf not installed. Install with: brew install fzf")
        return

    if result.returncode != 0:
        return  # Esc pressed

    selection = result.stdout.strip()
    if not selection:
        return

    target = selection.split("|")[0]  # "session:index" or "session:new"
    sess, win = target.split(":", 1)

    # Write switch command to temp file — tmux binding executes it after popup closes
    switch_file = os.path.expanduser("~/.config/mux/.dashboard-switch")
    if win == "new":
        path = projects.get(sess, {}).get("path", "")
        if not path:
            path = f"/tmp"  # fallback for unknown projects
        with open(switch_file, "w") as f:
            f.write(f"tmux new-session -d -s '{sess}' -c '{path}'; tmux switch-client -t '={sess}'")
    elif sess == current:
        with open(switch_file, "w") as f:
            f.write(f"tmux select-window -t '={sess}:{win}'")
    else:
        with open(switch_file, "w") as f:
            f.write(f"tmux switch-client -t '={sess}:{win}'")

if __name__ == "__main__":
    main()
