#!/usr/bin/env python3
# tmuxls - tmux/screen sessions with a summary, graceful fallback when absent
# Usage: tmuxls [--screen] [--json]
import argparse, json, os, shutil, subprocess, sys

def tmux_sessions():
    r = subprocess.run(["tmux", "list-sessions", "-F",
                        "#{session_name}\t#{session_windows}\t#{session_attached}\t#{session_created}"],
                       capture_output=True, text=True)
    if r.returncode != 0:
        return None
    out = []
    for line in r.stdout.splitlines():
        parts = line.split("\t")
        if len(parts) == 4:
            out.append({"name": parts[0], "windows": int(parts[1]),
                        "attached": int(parts[2]), "created": int(parts[3])})
    return out

def tmux_windows(sess):
    r = subprocess.run(["tmux", "list-windows", "-t", sess, "-F",
                        "#{window_index}:#{window_name} #{window_panes}p #{window_active}"],
                       capture_output=True, text=True)
    return r.stdout.strip().splitlines() if r.returncode == 0 else []

def screen_sessions():
    r = subprocess.run(["screen", "-ls"], capture_output=True, text=True)
    out = []
    for line in r.stdout.splitlines():
        line = line.strip()
        if "." in line and ("(Attached)" in line or "(Detached)" in line):
            pid_name, _, state = line.partition("\t")
            out.append({"session": pid_name.strip(),
                        "attached": "Attached" in line})
    return out

def selftest():
    out = subprocess.run([sys.executable, os.path.abspath(__file__)],
                         capture_output=True, text=True)
    assert out.returncode == 0, out.stderr
    assert "tmux" in out.stdout.lower() or "session" in out.stdout.lower(), out.stdout
    out = subprocess.run([sys.executable, os.path.abspath(__file__), "--json"],
                         capture_output=True, text=True)
    assert out.returncode == 0 and out.stdout.strip().startswith("{")
    print("tmuxls selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="tmuxls",
        description="List tmux (or screen) sessions with a summary; graceful when neither is installed.")
    ap.add_argument("--screen", action="store_true", help="list screen sessions instead of tmux")
    ap.add_argument("--json", action="store_true", help="emit JSON")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    data = {"backend": None, "sessions": []}
    if not a.screen and shutil.which("tmux"):
        sess = tmux_sessions()
        data["backend"] = "tmux"
        if sess is None:
            data["sessions"] = []
        else:
            for s in sess:
                s["windows_detail"] = tmux_windows(s["name"])
                data["sessions"].append(s)
    elif shutil.which("screen"):
        data["backend"] = "screen"
        data["sessions"] = screen_sessions()
    if a.json:
        print(json.dumps(data, indent=2))
        return 0
    if data["backend"] is None:
        print("tmuxls: neither tmux nor screen is installed — no sessions to list.")
        print("Install tmux to manage persistent terminal sessions.")
        return 0
    if not data["sessions"]:
        print("tmuxls (%s): no sessions running." % data["backend"]); return 0
    print("tmuxls (%s): %d session(s)" % (data["backend"], len(data["sessions"])))
    for s in data["sessions"]:
        if data["backend"] == "tmux":
            import datetime
            created = datetime.datetime.fromtimestamp(s["created"]).strftime("%Y-%m-%d %H:%M")
            print("  %-20s %d window(s), attached: %d, created %s" %
                  (s["name"], s["windows"], s["attached"], created))
            for w in s.get("windows_detail", []):
                print("      %s" % w)
        else:
            print("  %-20s %s" % (s["session"], "attached" if s["attached"] else "detached"))
    return 0

if __name__ == "__main__":
    sys.exit(main())
