#!/bin/bash
# DCOG-OS Client launcher (macOS / Linux)
#
# TWO MODES (both are END-USER - the god panel is NEVER opened):
#   1) STANDALONE (own brain):   ./start.sh
#      -> starts the local daemon on 5318 in CLIENT MODE, opens the end-user panel (/app/). God panel DISABLED.
#   2) FRIEND (connect to the host's remote brain):  ./start.sh https://HOST-TUNNEL.trycloudflare.com
#      -> does NOT run a daemon; opens the host brain's /app/ panel directly (same-origin).
# (To see the god panel, the owner runs the binary DIRECTLY, not via start.sh.)
#
# To get a public address the owner runs:  bash expose-brain.sh   (shares the resulting https://... URL)

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$DIR"

BRAIN_URL="${1:-$DCOG_BRAIN_URL}"
BINARY_NAME="dcog-commander"
PORT="${DCOG_PORT:-5318}"

open_url() {
  local url="$1"
  if [[ "$OSTYPE" == "darwin"* ]]; then open "$url"
  elif command -v xdg-open >/dev/null; then xdg-open "$url"
  else echo "🌐 Open your browser at: $url"; fi
}

# ── FRIEND MODE: connect to the owner's remote brain (no local daemon) ──
if [ -n "$BRAIN_URL" ]; then
  BRAIN_URL="${BRAIN_URL%/}"
  echo "🔗 Connecting to the owner's brain: $BRAIN_URL"
  echo "   (Opening the end-user panel served by that brain.)"
  open_url "$BRAIN_URL/app/"
  echo "🟢 If the page asks for an address, paste: $BRAIN_URL"
  exit 0
fi

# ── OWNER MODE: run the local sovereign daemon ──
echo "🚀 Starting DCOG-OS Sovereign Daemon (port $PORT)..."

cleanup() {
  if [ -f daemon.pid ]; then
    PID=$(cat daemon.pid); echo ""; echo "🛑 Stopping daemon (PID: $PID)..."; kill "$PID" 2>/dev/null; rm -f daemon.pid
  fi
  exit 0
}
trap cleanup EXIT INT TERM

if [ ! -f "./$BINARY_NAME" ]; then
  if [ -f "../src-tauri/target/release/$BINARY_NAME" ]; then
    echo "💡 Copying release binary..."; cp "../src-tauri/target/release/$BINARY_NAME" ./
  elif [ -f "../src-tauri/target/debug/$BINARY_NAME" ]; then
    echo "💡 Copying debug binary..."; cp "../src-tauri/target/debug/$BINARY_NAME" ./
  else
    echo "❌ $BINARY_NAME not found. Build first: cargo build --manifest-path ../src-tauri/Cargo.toml --release"
    exit 1
  fi
fi
chmod +x "./$BINARY_NAME"

# End-user device: god panel and ALL god authority are DISABLED (client mode).
# (To see the god panel, the owner runs the binary DIRECTLY: ./src-tauri/target/release/dcog-commander)
DCOG_CLIENT_MODE=1 ./$BINARY_NAME &
DAEMON_PID=$!
echo $DAEMON_PID > daemon.pid

echo "📡 Waiting for the daemon to come up on port $PORT..."
for i in $(seq 1 15); do sleep 1; curl -s -o /dev/null "http://127.0.0.1:$PORT/api/lock_status" 2>/dev/null && break; done

# Open the END-USER panel only. (God panel is DISABLED on this device — client mode.)
open_url "http://127.0.0.1:$PORT/app/"

echo "🟢 DCOG-OS started (end-user mode, PID: $DAEMON_PID)."
echo "   Panel: http://127.0.0.1:$PORT/app/"
echo "Press Ctrl+C to stop."

while kill -0 $DAEMON_PID 2>/dev/null; do sleep 1; done
