#!/usr/bin/env python3
import sys
import subprocess
import argparse

def run_tmux(args):
    """Run a tmux command and return output."""
    cmd = ["tmux"] + args
    try:
        res = subprocess.run(cmd, capture_output=True, text=True, check=True)
        return res.stdout.strip()
    except subprocess.CalledProcessError as e:
        return f"Error: {e.stderr.strip()}"

def list_sessions():
    """List active sessions."""
    output = run_tmux(["ls"])
    if "no server running" in output or "Error" in output:
        print("No active tmux sessions found.")
    else:
        print(output)

def view_pane(session):
    """Capture pane content."""
    # -p: print to stdout
    # -J: join lines (optional, but sometimes better for wrapping)
    # -e: include escape sequences? No, text is better for LLM.
    output = run_tmux(["capture-pane", "-pt", session])
    
    # Filter out empty lines to save context? 
    # For now, print raw, but maybe last 30 lines is enough?
    lines = output.splitlines()
    # Trim empty trailing lines
    while lines and not lines[-1].strip():
        lines.pop()
        
    print(f"--- Tmux Session: {session} (Last {len(lines)} lines) ---")
    print("\n".join(lines))

def send_keys(session, keys):
    """Send keys to session."""
    # check if session exists
    ls = run_tmux(["ls"])
    if session not in ls:
        print(f"Session '{session}' not found.")
        return

    # Use C-m for Enter
    res = run_tmux(["send-keys", "-t", session, keys, "C-m"])
    if not res: # Success returns empty stdout
        print(f"Sent '{keys}' to {session}")
        # Auto-show the result?
        # view_pane(session) 
        # Better to let the user decide or bot check again.
    else:
        print(res)

def main():
    parser = argparse.ArgumentParser(description="Tmux Bridge for Shell Bot")
    subparsers = parser.add_subparsers(dest="command")

    # ls
    subparsers.add_parser("ls", help="List sessions")

    # view
    view_parser = subparsers.add_parser("view", help="View session output")
    view_parser.add_argument("session", help="Session name")

    # send
    send_parser = subparsers.add_parser("send", help="Send text to session")
    send_parser.add_argument("session", help="Session name")
    send_parser.add_argument("text", help="Text to send")

    args = parser.parse_args()

    if args.command == "ls":
        list_sessions()
    elif args.command == "view":
        view_pane(args.session)
    elif args.command == "send":
        send_keys(args.session, args.text)
    else:
        parser.print_help()

if __name__ == "__main__":
    main()
