#!/usr/bin/env python

"""hx-helper - combines zellij, helix and broot.

This program is either run bei helix or by broot.

- Start zellij with two panes (layout snp.kdl), in the left pane is helix,
  the right pane is for cargo or bacon.
- Start helix
- Open a broot floating pane with Ctrl-y
- Select a file or directory with Alt-Enter (which quits broot)
- The working directory is automatically set in helix
- The file is opened in helix
- Set working directory at right pane with Backslash-d
- Send cargo commands to the right pane with Backslash ...
- Start bacon at the right pane with Backslash-B-b
- Run bacon commands with Backslash-B-...
- Stop bacon with Backslash-B-q

H. Hoegl, October 2026, <Hubert.Hoegl@tha.de>
"""

import os
import sys
import subprocess

TMP = "/tmp/tmp.TKcKueHdz4"
# These two files are used and deleted in the helix config
# ~/.config/helix/config.toml.
ZWD = "/tmp/zellij-wdir"
ZWF = "/tmp/zellij-file"


def str_to_cmd(s, nl=True):
    cmd = ""
    for c in s:
        cmd += "{} ".format(ord(c))
    if nl:
        cmd += "10"  # newline
    return cmd


if sys.argv[1] == "-d":
    # yazi, for helix :cd command (set working directory)
    with open(sys.argv[2]) as fo:
        dirname = os.path.dirname(fo.readline())
        sys.stdout.write(dirname)
        sys.stdout.flush()
elif sys.argv[1] == "-c":
    # yazi, for :open command
    with open(sys.argv[2]) as fo:
        fname = fo.readline()
        sys.stdout.write(fname)
        sys.stdout.flush()

elif sys.argv[1] == "-test":
    # --- NOT USED ---
    # ~/.config/helix/config.toml
    # run broot in zellij floating pane, return path via --outcmd. Use
    # alt-enter to quit broot.
    os.unlink(TMP)
    os.system(f"touch {TMP}")
    #
    # 'zellij run' immediately returns!
    # cmd = f"zellij run --floating --close-on-exit -- broot --outcmd {TMP}"
    cmd = f"zellij action new-pane -f -c -b -n 'broot' -- broot --outcmd {TMP}"
    os.system(cmd)
    with open(TMP) as fo:
        cmd = fo.readline().split()
        sys.stdout.write(cmd[1])
        sys.stdout.flush()

elif sys.argv[1] == "-zs":
    # This starts broot in a floating pane from helix,
    # see ~/.config/helix/config.toml
    cmd = "zellij action new-pane -f -c -b --width 60 --height 45 -n 'broot' -- broot"
    # must be blocking!
    subprocess.run(cmd.split(), check=False)

elif sys.argv[1] == "-be":
    # Alt-Enter in broot runs `hx-helper -be {file}`. See config file
    # ~/.config/broot/verbs.hjson. sys.argv[2] is either a directory
    # or a directory+filename
    if os.path.isdir(sys.argv[2]):
        with open(ZWF, "w") as fd:
            fd.write(sys.argv[2])
        with open(ZWD, "w") as fd:
            fd.write(sys.argv[2])
    if os.path.isfile(sys.argv[2]):
        with open(ZWF, "w") as fd:
            fd.write(sys.argv[2])
        with open(ZWD, "w") as fd:
            fd.write(os.path.dirname(sys.argv[2]))

# "zellij send to other pane"
elif sys.argv[1] == "-stp":
    if sys.argv[2] == "#setcwd":
        # used for special commands (start with #)
        cwd = os.getcwd()
        cmd = str_to_cmd("cd " + cwd)
        x = f"zellij action move-focus right; zellij action write {cmd}; zellij action move-focus left;"
        os.system(x)
    elif sys.argv[2].startswith("!"):
        # used for bacon single character commands (start with !)
        cmd = str_to_cmd(sys.argv[2][1:], nl=False)
        x = f"zellij action move-focus right; zellij action write {cmd}; zellij action move-focus left;"
        os.system(x)
    else:
        # used for normal shell commands
        cmd = str_to_cmd(sys.argv[2])
        x = f"zellij action move-focus right; zellij action write {cmd}; zellij action move-focus left;"
        os.system(x)

os._exit(0)
