#!/usr/bin/env bash
# Start CNPERP LAN server (keep terminal open, or use systemd cnperp-local)
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="${INSTALL_ROOT:-}"
if [[ -z "$ROOT" ]]; then
  ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
fi
if [[ ! -f "$ROOT/app/main.py" ]]; then
  for candidate in /opt/CNPERP "$HOME/CNPERP"; do
    if [[ -f "$candidate/app/main.py" ]]; then ROOT="$candidate"; break; fi
  done
fi
[[ -f "$ROOT/app/main.py" ]] || { echo "CNPERP not found. Run install-cnperp-local.sh first."; exit 1; }

cd "$ROOT"
PORT=8010
if [[ -f "$ROOT/.env" ]]; then
  val="$(grep -E '^\s*APP_PORT\s*=' "$ROOT/.env" | head -1 | cut -d= -f2 | tr -d ' \r')"
  [[ -n "$val" ]] && PORT="$val"
fi

UVICORN="$ROOT/.venv/bin/uvicorn"
[[ -x "$UVICORN" ]] || { echo "Run install-cnperp-local.sh first (.venv missing)."; exit 1; }

LAN_IP=""
if command -v hostname >/dev/null; then
  LAN_IP="$(hostname -I 2>/dev/null | awk '{print $1}' || true)"
fi
if [[ -z "$LAN_IP" ]] && [[ "$(uname -s)" == "Darwin" ]]; then
  LAN_IP="$(ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null || true)"
fi

mkdir -p "$ROOT/logs"
echo ""
echo "========================================"
echo "  CNPERP Local Server"
echo "========================================"
echo "  This machine:  http://localhost:${PORT}"
[[ -n "$LAN_IP" ]] && echo "  LAN users:     http://${LAN_IP}:${PORT}"
echo "  Setup:         http://localhost:${PORT}/setup"
echo ""
echo "  Cloud sync:    enabled — transactions push to online hub"
echo "  Keep this terminal open (Ctrl+C to stop)."
echo ""

export PYTHONPATH="$ROOT"
exec "$UVICORN" app.main:app --host 0.0.0.0 --port "$PORT" --workers 1
