#!/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"
SITE_URL="https://pp-planer.ddev.site"
cd "$PROJECT_DIR"

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

if ! command -v ddev >/dev/null 2>&1; then
    echo -e "${RED}✗ DDEV ist nicht installiert.${NC}"
    echo ""
    echo -e "  Installieren mit Homebrew:"
    echo -e "    ${CYAN}brew install ddev/ddev/ddev${NC}"
    echo ""
    echo -e "  Doku: ${CYAN}https://ddev.readthedocs.io/${NC}"
    exit 1
fi

if ! docker info >/dev/null 2>&1; then
    echo -e "${RED}✗ Docker läuft nicht.${NC}"
    echo -e "  Starte zuerst Docker Desktop / Colima / OrbStack."
    exit 1
fi

if [ -f "$PID_FILE" ]; then
    if kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
        echo -e "${RED}Dev-Worker laufen bereits (PID $(cat "$PID_FILE")).${NC}"
        echo -e "Stoppe zuerst mit: ${CYAN}./stop_dev.sh${NC}"
        exit 1
    fi
    echo -e "${YELLOW}▸ Verwaiste PID-Datei entfernt${NC}"
    rm -f "$PID_FILE"
fi

echo -e "${YELLOW}▸ DDEV starten (composer install, key:generate, migrate, npm build) …${NC}"
ddev start
echo -e "  ${GREEN}✓${NC} DDEV läuft"

echo -e "${YELLOW}▸ Dev-Worker im Hintergrund starten (queue + logs + vite HMR) …${NC}"
nohup ddev dev > "$LOG_FILE" 2>&1 &
DEV_PID=$!
sleep 1.5

if ! kill -0 "$DEV_PID" 2>/dev/null; then
    echo -e "  ${RED}✗${NC} Dev-Worker konnten nicht gestartet werden"
    echo -e "  Logs: ${CYAN}cat $LOG_FILE${NC}"
    exit 1
fi

echo "$DEV_PID" > "$PID_FILE"
echo -e "  ${GREEN}✓${NC} Dev-Worker (PID $DEV_PID)"

echo ""
echo -e "${GREEN}═══════════════════════════════════════════════${NC}"
echo -e "${GREEN}  Dev-Umgebung läuft!${NC}"
echo -e "${GREEN}═══════════════════════════════════════════════${NC}"
echo ""
echo -e "  App:   ${CYAN}${SITE_URL}${NC}"
echo -e "  Vite:  ${CYAN}${SITE_URL}:5173${NC}"
echo -e "  Mail:  ${CYAN}${SITE_URL}:8026${NC}  (Mailpit)"
echo -e "  Logs:  ${CYAN}tail -f .dev.log${NC}"
echo ""
echo -e "  Stop:  ${YELLOW}./stop_dev.sh${NC}"
echo ""
