#!/usr/bin/env sh
set -eu

COMMAND="${1:-status}"
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
AGENT_ROOT="$(CDPATH= cd -- "$SCRIPT_DIR/../../../.." && pwd)"
BUNDLED_PYTHON="$AGENT_ROOT/runtime/python/bin/python3"
PYTHON_EXE=""
CONFIG_PATH="${HOME}/.config/iuve-connect-agent/desktop-config.json"

emit_json() {
  printf '%s\n' "$1"
}

resolve_python() {
  if [ -x "$BUNDLED_PYTHON" ]; then
    PYTHON_EXE="$BUNDLED_PYTHON"
    return 0
  fi
  if [ -n "${IUVE_AGENT_PYTHON:-}" ] && [ -x "${IUVE_AGENT_PYTHON}" ]; then
    PYTHON_EXE="${IUVE_AGENT_PYTHON}"
    return 0
  fi
  if command -v python3 >/dev/null 2>&1; then
    PYTHON_EXE="$(command -v python3)"
    return 0
  fi
  return 1
}

invoke_agent_module() {
  export PYTHONPATH="$AGENT_ROOT/vendor:$AGENT_ROOT${PYTHONPATH:+:$PYTHONPATH}"
  (
    cd "$AGENT_ROOT"
    exec "$PYTHON_EXE" -m iuve_connect_agents.desktop.app "$@"
  )
}

open_iuve_connect_web() {
  open_bin="$(command -v open 2>/dev/null || true)"
  if [ -n "$open_bin" ]; then
    "$open_bin" "https://www.iuve.eu/app/connect" >/dev/null 2>&1 || true
  fi
}

resolve_console_app() {
  for candidate in \
    "${HOME}/Applications/IuVe Connect Agent.app" \
    "$AGENT_ROOT/Applications/IuVe Connect Agent.app" \
    "$SCRIPT_DIR/IuVe Connect Agent.app"
  do
    if [ -d "$candidate" ] && [ -x "$candidate/Contents/MacOS/IuVeConnectAgent" ]; then
      printf '%s\n' "$candidate"
      return 0
    fi
  done
  return 1
}

open_native_console() {
  # Prefer .app (Dock / Spotlight). Fallback: launch-console via Python.
  if APP_PATH="$(resolve_console_app)"; then
    open_bin="$(command -v open 2>/dev/null || true)"
    if [ -n "$open_bin" ]; then
      "$open_bin" "$APP_PATH" >/dev/null 2>&1 || true
      esc="$(printf '%s' "$APP_PATH" | sed 's/\\/\\\\/g; s/"/\\"/g')"
      emit_json "{\"ok\":true,\"adapter\":\"macos\",\"ui_surface\":\"native_console\",\"phase\":\"C.3\",\"app\":\"${esc}\"}"
      return 0
    fi
  fi
  if ! resolve_python; then
    emit_json '{"ok":false,"error":"python_unavailable","ui_surface":"native_console"}'
    return 1
  fi
  export IUVE_AGENT_PYTHON="$PYTHON_EXE"
  export PYTHONPATH="$AGENT_ROOT/vendor:$AGENT_ROOT${PYTHONPATH:+:$PYTHONPATH}"
  (
    cd "$AGENT_ROOT"
    nohup "$PYTHON_EXE" -m iuve_connect_agents.desktop.ui_bridge --launch-console --no-webview \
      --config "$CONFIG_PATH" \
      >>"${HOME}/.config/iuve-connect-agent/ui-bridge.log" 2>&1 &
  )
  emit_json '{"ok":true,"adapter":"macos","ui_surface":"native_console","phase":"C.3","hint":"Console launched via ui_bridge --launch-console (no .app found)."}'
  return 0
}

case "$COMMAND" in
  status)
    if ! resolve_python; then
      emit_json '{"ok":false,"error":"python_unavailable","hint":"Install Python 3.10+ or set IUVE_AGENT_PYTHON"}'
      exit 1
    fi
    invoke_agent_module status --config "$CONFIG_PATH"
    ;;
  run)
    if ! resolve_python; then
      emit_json '{"ok":false,"error":"python_unavailable"}'
      exit 1
    fi
    invoke_agent_module run --config "$CONFIG_PATH"
    ;;
  pair)
    if ! resolve_python; then
      emit_json '{"ok":false,"error":"python_unavailable"}'
      exit 1
    fi
    if [ -z "${IUVE_PAIR_TOKEN:-}" ]; then
      emit_json '{"ok":false,"error":"pair_token_required","hint":"Export IUVE_PAIR_TOKEN before launcher pair"}'
      exit 2
    fi
    invoke_agent_module pair --config "$CONFIG_PATH" --pair-token "${IUVE_PAIR_TOKEN}"
    ;;
  console)
    # Phase C.3: native console is default. Opt out with IUVE_MAC_NATIVE_CONSOLE=0.
    if [ "${IUVE_MAC_NATIVE_CONSOLE:-1}" = "0" ] || [ "${IUVE_MAC_NATIVE_CONSOLE:-}" = "false" ]; then
      open_iuve_connect_web
      emit_json '{"ok":true,"adapter":"macos","ui_surface":"web_connect","hint":"IUVE_MAC_NATIVE_CONSOLE=0 — opened Connect web."}'
      exit 0
    fi
    open_native_console
    exit $?
    ;;
  dry-run)
    if [ -x "$BUNDLED_PYTHON" ] || [ -x "$AGENT_ROOT/runtime/python/bin/python3" ]; then
      emit_json '{"ok":true,"adapter":"macos","mode":"active_runtime_wiring","python_required":false,"bundled_python":true,"ui_surface":"native_console","phase":"C.3","capabilities":["status","run","pair","dry-run","start","stop","console"]}'
    else
      emit_json '{"ok":true,"adapter":"macos","mode":"active_runtime_wiring","python_required":true,"bundled_python":false,"ui_surface":"native_console","phase":"C.3","capabilities":["status","run","pair","dry-run","start","stop","console"]}'
    fi
    ;;
  start)
    if ! resolve_python; then
      emit_json '{"ok":false,"error":"python_unavailable"}'
      exit 1
    fi
    export PYTHONPATH="$AGENT_ROOT/vendor:$AGENT_ROOT${PYTHONPATH:+:$PYTHONPATH}"
    nohup "$PYTHON_EXE" -m iuve_connect_agents.desktop.app run --config "$CONFIG_PATH" \
      >>"${HOME}/.config/iuve-connect-agent/desktop-agent.log" 2>&1 &
    if [ "${IUVE_MAC_NATIVE_CONSOLE:-1}" = "0" ] || [ "${IUVE_MAC_NATIVE_CONSOLE:-}" = "false" ]; then
      open_iuve_connect_web
      emit_json '{"ok":true,"adapter":"macos","started":true,"mode":"background_run","ui_surface":"web_connect"}'
      exit 0
    fi
    open_native_console
    exit $?
    ;;
  stop)
    pkill -f "iuve_connect_agents.desktop.app run" 2>/dev/null || true
    pkill -f "iuve_connect_agents.desktop.ui_bridge" 2>/dev/null || true
    emit_json '{"ok":true,"adapter":"macos","stopped":true,"note":"best_effort_process_stop"}'
    ;;
  install-console)
    sh "$SCRIPT_DIR/install_console_app.sh" "$AGENT_ROOT"
    ;;
  *)
    emit_json '{"ok":false,"error":"unsupported_command","allowed":["status","run","pair","start","stop","dry-run","console","install-console"]}'
    exit 2
    ;;
esac
