#!/bin/bash
# ==============================================================================
# School Management System - macOS Installer
# Requires Docker Desktop for Mac.
# ==============================================================================
set -e

INSTALL_DIR="$HOME/.school-system"
DEFAULT_PORT="18080"
PROJECT_NAME="school-system-production"
REGISTRY="registry.yaasabatech.ideasgh.com"
REGISTRY_USER="school-installer"
REGISTRY_PASS="ChangeThisToAStrongPassword"
COMPOSE_URL="https://sms.yaasabatech.ideasgh.com/downloads/docker-compose.yml"

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

echo -e "${CYAN}${BOLD}====================================================${NC}"
echo -e "${CYAN}${BOLD}   School Management System - macOS Installer${NC}"
echo -e "${CYAN}${BOLD}====================================================${NC}"

# macOS check
if [ "$(uname)" != "Darwin" ]; then
    echo -e "${RED}This installer is for macOS only.${NC}"
    exit 1
fi

# ==============================================================================
# [1/6] Docker check
# ==============================================================================
echo -e "\n${YELLOW}[1/6] Checking Docker Desktop...${NC}"

if ! command -v docker >/dev/null 2>&1; then
    echo -e "${RED}Docker Desktop is not installed.${NC}"
    echo ""
    echo "Install it first:"
    echo "  1. Open: https://www.docker.com/products/docker-desktop/"
    echo "  2. Download the Apple Silicon or Intel version"
    echo "  3. Drag Docker to Applications and launch it"
    echo "  4. Re-run this installer"
    echo ""
    read -rp "Press Enter to open the download page in your browser, or Ctrl+C to exit..."
    open "https://www.docker.com/products/docker-desktop/"
    exit 1
fi

if ! docker info >/dev/null 2>&1; then
    echo -e "${RED}Docker Desktop is installed but not running.${NC}"
    echo "Launch it from Applications, wait for the whale icon to stop animating, then re-run."
    read -rp "Press Enter to open Docker Desktop..."
    open -a Docker
    exit 1
fi

if ! docker compose version >/dev/null 2>&1; then
    echo -e "${RED}Docker Compose v2 not found.${NC}"
    echo "Update Docker Desktop to the latest version."
    exit 1
fi
echo -e "${GREEN}✓ Docker Desktop is running.${NC}"

# ==============================================================================
# [2/6] Prepare directory
# ==============================================================================
echo -e "\n${YELLOW}[2/6] Preparing ${INSTALL_DIR}...${NC}"
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"
mkdir -p data backups

# ==============================================================================
# [3/6] Download compose + create .env
# ==============================================================================
echo -e "\n${YELLOW}[3/6] Downloading configuration...${NC}"
curl -fsSL "$COMPOSE_URL" -o docker-compose.yml

if [ ! -f .env ]; then
    cat > .env <<EOF
SCHOOL_SYSTEM_PORT=$DEFAULT_PORT
JWT_SECRET=$(openssl rand -hex 32)
EOF
fi

# ==============================================================================
# [4/6] Port check
# ==============================================================================
echo -e "\n${YELLOW}[4/6] Validating port...${NC}"
TARGET_PORT=$(grep "^SCHOOL_SYSTEM_PORT=" .env | cut -d '=' -f2 | tr -d ' "\r\n')

if lsof -i ":${TARGET_PORT}" >/dev/null 2>&1; then
    ALT=$TARGET_PORT
    while lsof -i ":${ALT}" >/dev/null 2>&1; do ALT=$((ALT + 1)); done
    echo -e "${YELLOW}Port ${TARGET_PORT} busy, using ${ALT}${NC}"
    sed -i '' "s/^SCHOOL_SYSTEM_PORT=.*/SCHOOL_SYSTEM_PORT=$ALT/" .env
    TARGET_PORT=$ALT
fi
echo -e "${GREEN}✓ Host port: ${TARGET_PORT}${NC}"

# ==============================================================================
# [5/6] Registry login + pull
# ==============================================================================
echo -e "\n${YELLOW}[5/6] Authenticating with registry...${NC}"
echo "$REGISTRY_PASS" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin

echo -e "\n${YELLOW}[6/6] Pulling image and starting...${NC}"
docker compose -p "$PROJECT_NAME" down --remove-orphans 2>/dev/null || true
docker compose -p "$PROJECT_NAME" pull
docker compose -p "$PROJECT_NAME" up -d --force-recreate

# ==============================================================================
# Management scripts
# ==============================================================================
cat > "$INSTALL_DIR/start.sh" <<EOF
#!/bin/bash
cd "$INSTALL_DIR"
docker compose -p $PROJECT_NAME up -d
echo "Started. Access: http://localhost:$TARGET_PORT"
EOF

cat > "$INSTALL_DIR/stop.sh" <<EOF
#!/bin/bash
cd "$INSTALL_DIR"
docker compose -p $PROJECT_NAME down
echo "Stopped."
EOF

cat > "$INSTALL_DIR/restart.sh" <<EOF
#!/bin/bash
cd "$INSTALL_DIR"
docker compose -p $PROJECT_NAME restart
EOF

cat > "$INSTALL_DIR/update.sh" <<EOF
#!/bin/bash
cd "$INSTALL_DIR"
echo "$REGISTRY_PASS" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin
docker compose -p $PROJECT_NAME pull
docker compose -p $PROJECT_NAME up -d --force-recreate
echo "Updated."
EOF

cat > "$INSTALL_DIR/backup.sh" <<'EOF'
#!/bin/bash
cd "$(dirname "$0")"
STAMP=$(date +%Y%m%d_%H%M%S)
mkdir -p backups
C=$(docker compose -p school-system-production ps -q school-system)
[ -z "$C" ] && { echo "Container not running."; exit 1; }
docker exec "$C" sh -c "cp /app/data/school.db /app/data/backup-${STAMP}.db"
docker cp "$C:/app/data/backup-${STAMP}.db" "backups/school_${STAMP}.db"
echo "Backup: backups/school_${STAMP}.db"
EOF

cat > "$INSTALL_DIR/uninstall.sh" <<'EOF'
#!/bin/bash
read -rp "Backup before uninstall? [1=yes / 2=no / 3=cancel]: " c
cd "$(dirname "$0")"
case "$c" in
  1)
    mkdir -p backups
    C=$(docker compose -p school-system-production ps -q school-system 2>/dev/null || true)
    if [ -n "$C" ]; then
      docker exec "$C" sh -c "cp /app/data/school.db /app/data/pre-uninstall.db" 2>/dev/null || true
      docker cp "$C:/app/data/pre-uninstall.db" "backups/school_pre_uninstall_$(date +%Y%m%d_%H%M%S).db" 2>/dev/null || true
    fi
    docker compose -p school-system-production down --remove-orphans
    docker volume rm school-system-data 2>/dev/null || true
    find . -mindepth 1 -maxdepth 1 ! -name "backups" -exec rm -rf {} + 2>/dev/null || true
    ;;
  2)
    read -rp "Type DELETE to confirm: " x
    [ "$x" != "DELETE" ] && exit 0
    docker compose -p school-system-production down --remove-orphans
    docker volume rm school-system-data 2>/dev/null || true
    cd "$HOME" && rm -rf "$HOME/.school-system"
    ;;
  *) exit 0 ;;
esac
echo "Uninstall complete."
EOF

chmod +x "$INSTALL_DIR"/*.sh
echo -e "${GREEN}✓ Management scripts created.${NC}"

# ==============================================================================
# Health check
# ==============================================================================
echo -e "\n${YELLOW}Verifying health...${NC}"
HEALTHY=false
for i in $(seq 1 30); do
    if curl -sf "http://localhost:${TARGET_PORT}/health" 2>/dev/null | grep -q '"status"'; then
        HEALTHY=true
        break
    fi
    sleep 1
done

echo ""
if [ "$HEALTHY" = true ]; then
    echo -e "${GREEN}${BOLD}✓ Installation Successful!${NC}"
else
    echo -e "${YELLOW}⚠ Container started but health check did not respond.${NC}"
fi

echo ""
echo -e "Access:  ${CYAN}http://localhost:${TARGET_PORT}${NC}"
echo ""
echo "Scripts in $INSTALL_DIR:"
echo "  ./start.sh     ./stop.sh     ./restart.sh"
echo "  ./update.sh    ./backup.sh   ./uninstall.sh"
echo ""

# Auto-open browser
open "http://localhost:${TARGET_PORT}"
