#!/usr/bin/env python3

import os
import sys
import subprocess
import argparse
from pathlib import Path

def get_session_dir():
    """Get the session directory, preferring XDG_RUNTIME_DIR"""
    runtime_dir = os.environ.get('XDG_RUNTIME_DIR', '/tmp')
    return Path(runtime_dir) / 'simple-dtach-sessions'

def list_sessions():
    """List all active sessions"""
    session_dir = get_session_dir()
    if not session_dir.exists():
        print("No active sessions")
        return
    
    sessions = [f.name for f in session_dir.iterdir() if f.is_socket()]
    if sessions:
        print("Active sessions:")
        for session in sorted(sessions):
            print(f"  {session}")
    else:
        print("No active sessions")

def attach_or_create_session(session_name, command=None, debug=False):
    """Attach to existing session or create new one"""
    session_dir = get_session_dir()
    session_dir.mkdir(parents=True, exist_ok=True)
    socket_path = session_dir / session_name
    
    if debug:
        print(f"Debug: Session directory: {session_dir}")
        print(f"Debug: Socket path: {socket_path}")
        print(f"Debug: Socket exists: {socket_path.exists()}")
    
    if command:
        # Create/attach with specific command
        cmd_list = ['dtach', '-A', str(socket_path), '-e', '^T'] + command
        print(f"Starting '{session_name}' with command: {' '.join(command)} (Ctrl+T to detach)")
        if debug:
            print(f"Debug: Running command: {' '.join(cmd_list)}")
        subprocess.run(cmd_list)
    else:
        # Just attach or create with bash
        if socket_path.exists():
            cmd_list = ['dtach', '-a', str(socket_path), '-e', '^T']
            print(f"Attaching to '{session_name}'... (Ctrl+T to detach)")
            if debug:
                print(f"Debug: Running command: {' '.join(cmd_list)}")
            subprocess.run(cmd_list)
        else:
            cmd_list = ['dtach', '-A', str(socket_path), '-e', '^T', 'bash']
            print(f"Session '{session_name}' doesn't exist. Creating with bash... (Ctrl+T to detach)")
            if debug:
                print(f"Debug: Running command: {' '.join(cmd_list)}")
            subprocess.run(cmd_list)

def main():
    parser = argparse.ArgumentParser(
        description='Simple dtach wrapper for persistent sessions',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  sdetach                           - attach to 'default' session (creates if needed)
  sdetach --name lyrics             - attach to 'lyrics' session (creates if needed)
  sdetach -n server python app.py   - create 'server' session running python app.py
  sdetach --list                    - show active sessions  
        """
    )
    
    parser.add_argument('--list', '-l', action='store_true', help='List active sessions')
    parser.add_argument('--name', '-n', help='Session name (default: "default")')
    parser.add_argument('--debug', '-d', action='store_true', help='Show debug output including exact commands')
    parser.add_argument('command', nargs='*', help='Command to run in session')
    
    if len(sys.argv) == 1:
        # No arguments - use default session
        attach_or_create_session('default')
        return
    
    args = parser.parse_args()
    
    if args.list:
        list_sessions()
    else:
        session_name = args.name or 'default'
        command = args.command if args.command else None
        attach_or_create_session(session_name, command, args.debug)

if __name__ == '__main__':
    main()