#!/usr/bin/env bash
set -euo pipefail

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
PID_FILE="$PROJECT_DIR/.dev.pid"
LOG_FILE="$PROJECT_DIR/.dev.log"
cd "$PROJECT_DIR"

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

KEEP_DDEV=false
if [ "${1:-}" = "--keep-ddev" ]; then
    KEEP_DDEV=true
fi

if [ -f "$PID_FILE" ]; then
    DEV_PID="$(cat "$PID_FILE")"
    if kill -0 "$DEV_PID" 2>/dev/null; then
        kill -TERM "$DEV_PID" 2>/dev/null || true
        for _ in 1 2 3 4 5; do
            kill -0 "$DEV_PID" 2>/dev/null || break
            sleep 0.5
        done
        kill -0 "$DEV_PID" 2>/dev/null && kill -KILL "$DEV_PID" 2>/dev/null || true
        echo -e "  ${YELLOW}▸${NC} Dev-Worker (PID $DEV_PID) gestoppt"
    else
        echo -e "  ${YELLOW}▸${NC} Dev-Worker waren bereits beendet"
    fi
    rm -f "$PID_FILE"
else
    echo -e "  ${YELLOW}▸${NC} Keine PID-Datei – keine laufenden Dev-Worker"
fi

rm -f "$LOG_FILE"

if [ "$KEEP_DDEV" = true ]; then
    echo ""
    echo -e "${GREEN}Dev-Worker gestoppt. DDEV läuft weiter.${NC}"
    echo -e "  Komplett stoppen: ${CYAN}ddev stop${NC}"
    echo ""
    exit 0
fi

if command -v ddev >/dev/null 2>&1; then
    echo -e "${YELLOW}▸ DDEV stoppen …${NC}"
    ddev stop >/dev/null 2>&1 || true
    echo -e "  ${GREEN}✓${NC} DDEV gestoppt"
fi

echo ""
echo -e "${GREEN}Dev-Umgebung komplett gestoppt.${NC}"
echo -e "  Tipp: ${CYAN}./stop_dev.sh --keep-ddev${NC} stoppt nur die Worker (DDEV bleibt an)"
echo ""
