#!/usr/bin/env bash
# CA Automator — one-shot local launcher.
# Usage: ./start.sh   (from the ca-automator project root)
set -e

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PORT="${1:-8000}"
WORKER_PID_FILE="$DIR/data/worker.pid"

# Local secrets (e.g. GROQ_API_KEY for the site chatbot) — data/.env is
# instance-specific, never part of any template handed to another firm.
# Sourced into this shell so both the web server and worker below inherit it.
if [ -f "$DIR/data/.env" ]; then
  set -a
  # shellcheck disable=SC1091
  source "$DIR/data/.env"
  set +a
fi

# free the port if a previous run is still holding it
lsof -ti:"$PORT" -sTCP:LISTEN | xargs -r kill 2>/dev/null || true
sleep 1

cd "$DIR/server"
nohup "$DIR/venv/bin/python3" run.py serve "$PORT" > "$DIR/server.log" 2>&1 &
disown
sleep 1.5

if lsof -ti:"$PORT" -sTCP:LISTEN > /dev/null; then
  echo "CA Automator is running: http://localhost:$PORT"
  open "http://localhost:$PORT" 2>/dev/null || true
else
  echo "Failed to start — check $DIR/server.log"
  tail -n 40 "$DIR/server.log"
  exit 1
fi

# The night worker (deadline sweep -> in-app + email alerts, job queue,
# nightly backup) is a separate long-running process from the web server —
# without it, "Alerts" only ever fills from synchronous events (a contact
# form submit, a job application) and every deadline/reminder notification
# silently never gets raised. Idempotent: kill whatever PID the last run
# left behind first, so re-running start.sh never stacks up duplicate
# workers double-sending the same reminders.
mkdir -p "$DIR/data"
if [ -f "$WORKER_PID_FILE" ]; then
  kill "$(cat "$WORKER_PID_FILE")" 2>/dev/null || true
fi
nohup "$DIR/venv/bin/python3" run.py worker > "$DIR/worker.log" 2>&1 &
disown
echo $! > "$WORKER_PID_FILE"
echo "Background worker running (deadline alerts, job queue, backups) — pid $(cat "$WORKER_PID_FILE")"
