#!/usr/bin/env bash
# Start/stop do live view de wireframes (lumo-mockup) — ver
# references/wireframe-companion.md para quando/como oferecer isto.
#
# Uso:
#   wireframe-server.sh start [<dir-de-wireframes>]   # default: ./escopo/wireframes
#   wireframe-server.sh stop

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PID_FILE="/tmp/lumo-wireframe-server.pid"
URL_FILE="/tmp/lumo-wireframe-server.url"
LOG_FILE="/tmp/lumo-wireframe-server.log"

cmd="${1:-}"

case "$cmd" in
  start)
    dir="${2:-./escopo/wireframes}"

    if [[ -f "$PID_FILE" ]] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
      echo "Já rodando: $(cat "$URL_FILE" 2>/dev/null || echo '(url desconhecida, ver ' "$LOG_FILE" ')')"
      exit 0
    fi

    nohup node "$SCRIPT_DIR/wireframe-server.cjs" "$dir" > "$LOG_FILE" 2>&1 &
    pid=$!
    echo "$pid" > "$PID_FILE"

    url=""
    for _ in $(seq 1 50); do
      if [[ -s "$LOG_FILE" ]]; then
        url="$(grep -m1 '^LIVE-VIEW: ' "$LOG_FILE" 2>/dev/null | sed 's/^LIVE-VIEW: //')"
        [[ -n "$url" ]] && break
      fi
      if ! kill -0 "$pid" 2>/dev/null; then
        echo "Servidor caiu ao iniciar. Log:" >&2
        cat "$LOG_FILE" >&2
        rm -f "$PID_FILE"
        exit 1
      fi
      sleep 0.1
    done

    if [[ -z "$url" ]]; then
      echo "Timeout esperando o servidor iniciar. Log:" >&2
      cat "$LOG_FILE" >&2
      exit 1
    fi

    echo "$url" > "$URL_FILE"
    echo "$url"
    ;;

  stop)
    if [[ -f "$PID_FILE" ]]; then
      pid="$(cat "$PID_FILE")"
      kill "$pid" 2>/dev/null || true
      rm -f "$PID_FILE" "$URL_FILE"
      echo "Servidor parado."
    else
      echo "Nenhum servidor rodando."
    fi
    ;;

  *)
    echo "Uso: $0 start [<dir-de-wireframes>] | stop" >&2
    exit 1
    ;;
esac
