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

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
PID_FILE="$PROJECT_DIR/.dev.pid"
SITE_NAME="pp-planer"
cd "$PROJECT_DIR"

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

# ── Stale PID cleanup ──────────────────────────────────────
if [ -f "$PID_FILE" ]; then
    ALL_DEAD=true
    while read -r PID; do
        if kill -0 "$PID" 2>/dev/null; then
            ALL_DEAD=false
            break
        fi
    done < <(tr ' ' '\n' < "$PID_FILE")

    if [ "$ALL_DEAD" = true ]; then
        echo -e "${YELLOW}▸ Verwaiste PID-Datei entfernt${NC}"
        rm -f "$PID_FILE"
    else
        echo -e "${RED}Dev-Umgebung läuft bereits.${NC}"
        echo -e "Stoppe zuerst mit: ${CYAN}./stop_dev.sh${NC}"
        exit 1
    fi
fi

# ── Valet link ──────────────────────────────────────────────
echo -e "${YELLOW}▸ Valet-Link prüfen …${NC}"
if [ ! -L "$HOME/.config/valet/Sites/$SITE_NAME" ]; then
    valet link "$SITE_NAME" 2>/dev/null
    echo -e "  ${GREEN}✓${NC} Valet-Link erstellt: ${SITE_NAME}.test"
else
    echo -e "  ${GREEN}✓${NC} Valet-Link vorhanden"
fi

# ── Dependencies check ──────────────────────────────────────
if [ ! -d "node_modules" ]; then
    echo -e "${YELLOW}▸ npm install …${NC}"
    npm install --silent
    echo -e "  ${GREEN}✓${NC} Node-Module installiert"
fi

if [ ! -d "vendor" ]; then
    echo -e "${YELLOW}▸ composer install …${NC}"
    composer install --quiet
    echo -e "  ${GREEN}✓${NC} Composer-Pakete installiert"
fi

# ── APP_KEY check ───────────────────────────────────────────
if ! grep -q '^APP_KEY=base64:' .env 2>/dev/null; then
    echo -e "${YELLOW}▸ APP_KEY generieren …${NC}"
    php artisan key:generate --quiet
    echo -e "  ${GREEN}✓${NC} APP_KEY generiert"
fi

# ── Migrate ─────────────────────────────────────────────────
echo -e "${YELLOW}▸ Migrations ausführen …${NC}"
php artisan migrate --force --quiet
echo -e "  ${GREEN}✓${NC} Datenbank aktuell"

# ── Queue worker ────────────────────────────────────────────
echo -e "${YELLOW}▸ Queue-Worker starten …${NC}"
php artisan queue:listen --tries=1 --timeout=0 > /dev/null 2>&1 &
QUEUE_PID=$!
sleep 0.3
if kill -0 "$QUEUE_PID" 2>/dev/null; then
    echo -e "  ${GREEN}✓${NC} Queue-Worker (PID $QUEUE_PID)"
else
    echo -e "  ${RED}✗${NC} Queue-Worker konnte nicht gestartet werden"
    exit 1
fi

# ── Vite dev server ─────────────────────────────────────────
echo -e "${YELLOW}▸ Vite starten …${NC}"
npx --yes vite --port 5173 > /dev/null 2>&1 &
VITE_PID=$!
sleep 0.5
if kill -0 "$VITE_PID" 2>/dev/null; then
    echo -e "  ${GREEN}✓${NC} Vite (PID $VITE_PID)"
else
    echo -e "  ${RED}✗${NC} Vite konnte nicht gestartet werden"
    kill "$QUEUE_PID" 2>/dev/null || true
    exit 1
fi

# ── Save PIDs ───────────────────────────────────────────────
echo "$QUEUE_PID $VITE_PID" > "$PID_FILE"

echo ""
echo -e "${GREEN}═══════════════════════════════════════════════${NC}"
echo -e "${GREEN}  Dev-Umgebung läuft!${NC}"
echo -e "${GREEN}═══════════════════════════════════════════════${NC}"
echo ""
echo -e "  App:   ${CYAN}http://${SITE_NAME}.test${NC}"
echo -e "  Vite:  ${CYAN}http://localhost:5173${NC}"
echo ""
echo -e "  Stop:  ${YELLOW}./stop_dev.sh${NC}"
echo ""
