#!/usr/bin/env bash
# AI-PHONE LIVE — stop the pipeline server + DevOps API started by ./start.sh.
set -uo pipefail
PROJECT_DIR="$(dirname "$(readlink -f "$0")")"

stop_one() {
    local pidfile="$1" name="$2"
    if [ -f "$pidfile" ]; then
        local pid; pid="$(cat "$pidfile" 2>/dev/null)"
        if [ -n "$pid" ] && ps -p "$pid" >/dev/null 2>&1; then
            kill "$pid"; sleep 2
            if ps -p "$pid" >/dev/null 2>&1; then
                kill -9 "$pid"; sleep 1
                echo "$name force-killed (was PID $pid)"
            else
                echo "$name stopped (was PID $pid)"
            fi
        else
            echo "$name not running (stale pid file)"
        fi
        rm -f "$pidfile"
    else
        echo "$name: no pid file, nothing to stop"
    fi
}

stop_one "$PROJECT_DIR/flask_pid.txt" "pipeline server"
stop_one "$PROJECT_DIR/devops_pid.txt" "devops api"
