#!/usr/bin/env bash
set -e

show_game_guide() {
  echo ""
  echo "================================================================"
  echo "                     BATTLESHIPS GAME GUIDE"
  echo "================================================================"
  echo ""
  echo "GAME FLOW:"
  echo "  1. Wait for 'GAME STARTED' message from server"
  echo "  2. Place all your ships on the board (preparation phase)"
  echo "  3. Type 'READY' when done placing ships"
  echo "  4. Wait for opponent to be ready"
  echo "  5. When 'YOUR TURN' appears, fire at enemy positions"
  echo "  6. Game ends when all ships of one player are sunk"
  echo ""
  echo "SERVER MESSAGES:"
  echo "  GAME STARTED     - Game has begun, start placing ships"
  echo "  GAME OVER        - Game has ended"
  echo "  YOUR TURN        - It's your turn to fire"
  echo "  YOU WON          - You won the game!"
  echo "  OK <result>      - Command succeeded"
  echo "  KO <error>       - Command failed with error message"
  echo ""
  echo "================================================================"
  echo "                          COMMANDS"
  echo "================================================================"
  echo ""
  echo "INFORMATION COMMANDS (available anytime):"
  echo ""
  echo "  ?                     List all available commands"
  echo ""
  echo "  DIM                   Get board dimension (e.g., 10 for 10x10)"
  echo ""
  echo "  SHIPS                 List ships to place with counts"
  echo "                        Example response: B2 D2 S0 P3 C1"
  echo "                        Means: 2x Battleship, 2x Destroyer,"
  echo "                               0x Submarine, 3x Patrol, 1x Cruiser"
  echo ""
  echo "  SPARTS <ship>         Get ship parts/shape (relative positions)"
  echo "                        Example: SPARTS B -> A1 A2 A3 A4"
  echo ""
  echo "PREPARATION PHASE COMMANDS:"
  echo ""
  echo "  PLACE <ship> <pos> <dir>"
  echo "                        Place a ship on the board"
  echo "                        <ship>: Ship code (B, C, D, P, S)"
  echo "                        <pos>:  Position A1-J10 (row A-J, col 1-10)"
  echo "                        <dir>:  Direction N/R/U/D"
  echo "                                N = Normal (right)"
  echo "                                R = Reverse (left)"
  echo "                                U = Up"
  echo "                                D = Down"
  echo ""
  echo "  DEL <pos>             Delete ship at position"
  echo "                        Example: DEL A1"
  echo ""
  echo "  MSHIPS                List your currently placed ships"
  echo "                        Format: <code>,<pos>,<dir> ..."
  echo "                        Example: B,A1,N D,C3,D"
  echo ""
  echo "  READY                 Confirm placement and start game"
  echo "                        (All ships must be placed first)"
  echo ""
  echo "BATTLE PHASE COMMANDS:"
  echo ""
  echo "  FIRE <pos>            Fire at enemy position"
  echo "                        Example: FIRE B5"
  echo "                        Response: W (Water/Miss)"
  echo "                                  H (Hit)"
  echo "                                  S (Sunk)"
  echo ""
  echo "================================================================"
  echo "                        SHIP TYPES"
  echo "================================================================"
  echo ""
  echo "  Code  Name        Length  Description"
  echo "  ----  ----------  ------  ---------------------------"
  echo "  B     Battleship  4       Large warship"
  echo "  C     Cruiser     5       Largest ship"
  echo "  D     Destroyer   3       Medium escort ship"
  echo "  P     Patrol      2       Small patrol boat"
  echo "  S     Submarine   3       Underwater vessel"
  echo ""
  echo "  Note: Use SHIPS command to see how many of each to place."
  echo ""
}

show_help() {
  echo "Usage: $0 [options] <program> [args...]"
  echo ""
  echo "Options:"
  echo "  --help            Show this help message and exit"
  echo "  --guide           Show the game guide and exit"
  echo "  --manual          Run the agent in foreground for manual play (no program needed)"
  echo "  --no-cleanup      Skip cleanup of temporary directory after program ends"
  echo "  --agent <path>    Use specified agent binary instead of downloading"
  echo "  --prefix <prefix> Add prefix to player name (e.g., 'sm' -> user-sm-abc123)"
  echo ""
  echo "Examples:"
  echo "  $0 ./my_bot                      Run my_bot as the battleship player"
  echo "  $0 --manual                      Play manually via the agent in your terminal"
  echo "  $0 --guide                       Show game commands and rules"
  echo "  $0 --agent /tmp/agent ./my_bot   Use pre-downloaded agent"
  echo "  $0 --prefix sm ./smart_bot       Run with 'sm' prefix in player name"
}

MANUAL_MODE=false
NO_CLEANUP=false
AGENT_PATH=""
NAME_PREFIX=""

# Parse options
while [[ $# -gt 0 ]]; do
  case "$1" in
    --help)
      show_help
      exit 0
      ;;
    --guide)
      show_game_guide
      exit 0
      ;;
    --manual)
      MANUAL_MODE=true
      shift
      ;;
    --no-cleanup)
      NO_CLEANUP=true
      shift
      ;;
    --agent)
      if [ -z "$2" ] || [[ "$2" == --* ]]; then
        echo "Error: --agent requires a path argument" >&2
        exit 1
      fi
      AGENT_PATH="$2"
      shift 2
      ;;
    --prefix)
      if [ -z "$2" ] || [[ "$2" == --* ]]; then
        echo "Error: --prefix requires a value argument" >&2
        exit 1
      fi
      NAME_PREFIX="$2"
      shift 2
      ;;
    *)
      break
      ;;
  esac
done

if [ "$MANUAL_MODE" = false ] && [ "$#" -lt 1 ]; then
  echo "Usage: $0 [options] <program> [args...]"
  echo "Try '$0 --help' for more information."
  exit 1
fi

RUN_ID=$(openssl rand -hex 4)
echo "Run ID: $RUN_ID"

# Construct player name with optional prefix
if [ -n "$NAME_PREFIX" ]; then
  PLAYER_NAME="$(whoami)-${NAME_PREFIX}-${RUN_ID}"
else
  PLAYER_NAME="$(whoami)-${RUN_ID}"
fi
echo "Player name: $PLAYER_NAME"

TEMPORARY_DIRECTORY="$(mktemp -d)"/$RUN_ID
mkdir -p $TEMPORARY_DIRECTORY
echo "Temporary directory: $TEMPORARY_DIRECTORY"

if [ -n "$AGENT_PATH" ]; then
  if [ ! -x "$AGENT_PATH" ]; then
    echo "Error: Agent not found or not executable: $AGENT_PATH" >&2
    exit 1
  fi
  AGENT_BINARY="$AGENT_PATH"
  echo "Using provided agent: $AGENT_BINARY"
else
  echo "Downloading agent..."
  wget -q https://lode.delta-topgun.cz/assets/agent -O $TEMPORARY_DIRECTORY/agent
  echo "Agent downloaded."

  echo "Preparing agent..."
  chmod +x $TEMPORARY_DIRECTORY/agent
  AGENT_BINARY="$TEMPORARY_DIRECTORY/agent"
fi

if [ "$MANUAL_MODE" = true ]; then
  show_game_guide
  echo "================================================================"
  echo "Starting agent... (Ctrl+C to quit)"
  echo "================================================================"
  echo ""
  "$AGENT_BINARY" \
    -scheme wss \
    -addr lode.delta-topgun.cz \
    -name=$PLAYER_NAME
else
  mkfifo $TEMPORARY_DIRECTORY/agent_output $TEMPORARY_DIRECTORY/program_output
  echo "Agent prepared."

  echo "Starting agent..."        
  "$AGENT_BINARY" \
    -scheme wss \
    -addr lode.delta-topgun.cz \
    -name=$PLAYER_NAME \
    > $TEMPORARY_DIRECTORY/agent_output \
    < $TEMPORARY_DIRECTORY/program_output &
  echo "Agent started."

  echo "Starting program..."
  $@ \
    < $TEMPORARY_DIRECTORY/agent_output \
    > $TEMPORARY_DIRECTORY/program_output
  echo "Program ended."

  if [ "$NO_CLEANUP" = false ]; then
    echo "Cleaning up..."
    rm -rf $TEMPORARY_DIRECTORY
    echo "Cleanup completed."
  fi
fi

