# frozen_string_literal: true

require 'daytona'

daytona = Daytona::Daytona.new
sandbox = daytona.create

session_id = 'exec-session-1'
sandbox.process.create_session(session_id)

# Get the session details
session = sandbox.process.get_session(session_id)
puts session

# Execute first command in the session
first_command = sandbox.process.execute_session_command(
  session_id: session_id,
  req: Daytona::SessionExecuteRequest.new(command: 'export FOO=BAR')
)

if first_command.exit_code == 0
  puts first_command.output
else
  puts "Error: #{first_command.exit_code} #{first_command.stderr}"
end

# Get the session details again to see the command has been executed
session = sandbox.process.get_session(session_id)
puts session.commands

# Get the command details
command = sandbox.process.get_session_command(session_id: session_id, command_id: first_command.cmd_id)
puts command

# Execute second command in the session and observe the environment variable is set
second_command = sandbox.process.execute_session_command(
  session_id: session_id,
  req: Daytona::SessionExecuteRequest.new(command: 'echo $FOO')
)

if second_command.exit_code == 0
  puts second_command.output
else
  puts "Error: #{second_command.exit_code} #{second_command.stderr}"
end

# Get logs for the second command
logs = sandbox.process.get_session_command_logs(session_id: session_id, command_id: second_command.cmd_id)
puts "[STDOUT] #{logs.stdout}"
puts "[STDERR] #{logs.stderr}"

# Demonstrate sending input to an interactive command
puts "\n--- Testing send_session_command_input ---"
interactive_command = sandbox.process.execute_session_command(
  session_id: session_id,
  req: Daytona::SessionExecuteRequest.new(
    command: 'printf "Enter your name: \n" && read name && printf "Hello, %s\n" "$name"',
    run_async: true
  )
)

# Wait a moment for the command to start
sleep 1

# Send input to the command
puts 'Sending input to the command...'
sandbox.process.send_session_command_input(
  session_id: session_id,
  command_id: interactive_command.cmd_id,
  data: 'Alice'
)
puts 'Input sent to the command'

# Get logs for the interactive command asynchronously
puts 'Retrieving command logs...'
sandbox.process.get_session_command_logs_async(
  session_id: session_id,
  command_id: interactive_command.cmd_id,
  on_stdout: ->(log) { puts "[STDOUT]: #{log}" },
  on_stderr: ->(log) { puts "[STDERR]: #{log}" }
)
puts 'Command completed with interactive input'

# List active sessions
sessions = sandbox.process.list_sessions
puts sessions

# Delete the session
sandbox.process.delete_session(session_id)

# Cleanup resources
daytona.delete(sandbox)
