#!/bin/bash

# omarchy:summary=Open Game Vibes Studio, Omarchy's games and the ones made in ~/Games/vibes, in the current theme
# omarchy:args=[--url] [--new] [--agent <id>] [--model <id>] [game]
# omarchy:examples=omarchy games vibes launch | omarchy games vibes launch snake | omarchy games vibes launch --new --agent claude

# Game Vibes Studio runs a local server behind Chrome --app so the app can
# live-reload edits, stream changes through the default coding agent, toggle
# fullscreen, and quit cleanly without Super+W. --url keeps the static file://
# path for headless inspection with omarchy agent look page.

set -euo pipefail

print_url=""
new_game=false
agent=""
model=""
while (( $# > 0 )); do
  case "$1" in
  --url)
    print_url=1
    shift
    ;;
  --new)
    new_game=true
    shift
    ;;
  --agent)
    agent=${2:?--agent needs a value}
    shift 2
    ;;
  --model)
    model=${2:?--model needs a value}
    shift 2
    ;;
  --)
    shift
    break
    ;;
  -*)
    echo "Unknown option: $1" >&2
    exit 1
    ;;
  *)
    break
    ;;
  esac
done

vibes="$HOME/Games/vibes"
mkdir -p "$vibes"

# Every game loads three.js from ../three.min.js, so the games made here get
# the copy the shipped ones sit beside.
cp "$OMARCHY_PATH/default/games/vibes/three.min.js" "$vibes/three.min.js"

# A game is a folder named like a command, holding an index.html. One made
# here replaces the shipped game of its name, as a copy to keep working on
# does.
declare -A games=()
for page in "$OMARCHY_PATH/default/games/vibes"/*/index.html "$vibes"/*/index.html; do
  [[ -f $page ]] || continue
  dir=${page%/index.html}
  name=${dir##*/}
  [[ $name =~ ^[a-z0-9][a-z0-9-]*$ ]] && games[$name]=$dir
done

game=${1:-}
if [[ -n $game && -z ${games[$game]:-} ]]; then
  echo "No game called $game in Game Vibes" >&2
  exit 1
fi

if [[ -n $print_url ]]; then
  for name in "${!games[@]}"; do
    dir=${games[$name]}
    title=$(sed -n 's:.*<title>\(.*\)</title>.*:\1:p' "$dir/index.html" | head -1 | tr -d '\t')
    blurb=$(sed -n 's:.*<meta name="description" content="\([^"]*\)".*:\1:p' "$dir/index.html" | head -1 | tr -d '\t')
    icon=false
    [[ -f $dir/icon.svg ]] && icon=true
    printf '%s\t%s\t%s\t%s\t%s\n' "$name" "${title:-$name}" "$icon" "$dir" "$blurb"
  done | sort | jq -Rrn --rawfile page "$OMARCHY_PATH/default/games/vibes.html" '
    [inputs | split("\t") | {name: .[0], title: .[1], blurb: .[4], icon: (.[2] == "true"),
      url: ("file://" + (.[3] | split("/") | map(@uri) | join("/")))}]
    | tojson | gsub("<"; "\\u003c") as $games
    | $page | sub("/\\*GAMES\\*/\\[\\]"; $games)' >"$vibes/index.html"

  page="file://$(jq -rn --arg path "$vibes/index.html" '$path | split("/") | map(@uri) | join("/")')"
  url="$page#palette=$(omarchy-theme-color --all | jq -Rrn '[inputs | split("\t") | {(.[0]): .[1]}] | add | tojson | @uri')"
  [[ -z $game ]] || url+="&open=$game"
  printf '%s\n' "$url"
else
  # If Game Vibes Studio is already running, hand off the game to the existing
  # window instead of opening a duplicate one. When invoked by an agent inside
  # Studio (OMARCHY_GAME_VIBES_STUDIO=1), never spawn a second browser window.
  runtime_dir="${XDG_RUNTIME_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/run}"
  mkdir -p -m 700 "$runtime_dir"
  runtime_file="$runtime_dir/omarchy-game-vibes.json"
  if [[ -f $runtime_file && ! -L $runtime_file && -O $runtime_file ]]; then
    IFS=$'\t' read -r pid port ipc_token < <(jq -r '[.pid // "", .shellPort // "", .ipcToken // ""] | @tsv' "$runtime_file" 2>/dev/null) || true
    if [[ ${pid:-} =~ ^[0-9]+$ && ${port:-} =~ ^[0-9]+$ && -n ${ipc_token:-} ]] && kill -0 "$pid" 2>/dev/null; then
      keep_mode=false
      [[ ${OMARCHY_GAME_VIBES_STUDIO:-} == "1" ]] && keep_mode=true
      payload=$(jq -nc \
        --arg game "$game" \
        --argjson newGame "$new_game" \
        --arg agent "$agent" \
        --arg model "$model" \
        --argjson keepMode "$keep_mode" \
        '{game: $game, newGame: $newGame, agent: $agent, model: $model, keepMode: $keepMode}')
      if curl -fsS -m 2 -X POST "http://127.0.0.1:$port/ipc/open" \
        -H "Content-Type: application/json" \
        -H "X-Vibes-IPC: $ipc_token" \
        -d "$payload" >/dev/null 2>&1; then
        exit 0
      fi
    fi
  fi
  if [[ ${OMARCHY_GAME_VIBES_STUDIO:-} == "1" ]]; then
    exit 0
  fi

  ready_dir=$(mktemp -d "$runtime_dir/omarchy-game-vibes-ready.XXXXXX")
  chmod 700 "$ready_dir"
  ready_fifo="$ready_dir/ready"
  mkfifo -m 600 "$ready_fifo"
  trap 'rm -rf "$ready_dir"' EXIT

  server_args=(--ready-file "$ready_fifo")
  [[ -n $game ]] && server_args+=(--open "$game")
  [[ $new_game == "true" ]] && server_args+=(--new)
  [[ -n $agent ]] && server_args+=(--agent "$agent")
  [[ -n $model ]] && server_args+=(--model "$model")

  setsid node "$OMARCHY_PATH/default/games/vibes-server.mjs" "${server_args[@]}" </dev/null >/dev/null 2>&1 &
  ready_json=$(timeout 5 cat "$ready_fifo" || true)
  rm -rf "$ready_dir"
  trap - EXIT

  boot_url=$(jq -r '.bootUrl // empty' <<<"$ready_json" 2>/dev/null || true)
  if [[ -z $boot_url ]]; then
    echo "Failed to start Game Vibes Studio server" >&2
    exit 1
  fi

  exec omarchy-launch-webapp "$boot_url"
fi
