#!/usr/bin/env bash
#
# AI Code Toolkits - Installer (macOS / Linux)
# Cài đặt offline, chỉ cần Node.js >= 18
#
# Usage: bash install.sh
#

set -euo pipefail

INSTALL_DIR="$HOME/.ai-code-toolkits"

echo ""
echo "⚡ AI Code Toolkits — Installer"
echo ""

# Check node
if ! command -v node &> /dev/null; then
    echo "[ERROR] Node.js không tìm thấy"
    echo "Cài đặt: https://nodejs.org/en/download/"
    exit 1
fi

NODE_VERSION=$(node --version | sed 's/v//' | cut -d. -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
    echo "[ERROR] Cần Node.js >= 18 (hiện tại: $(node --version))"
    exit 1
fi

# Create install dir
echo "-> Cài đặt vào $INSTALL_DIR..."
mkdir -p "$INSTALL_DIR"

# Copy all files
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
FILES=("server.js" "patcher.js" "ag-injector.js" "auto-script.js" "index.html" "package.json" "install.ps1" "install.sh" "INSTALL_GUIDE.md")

for file in "${FILES[@]}"; do
    src="$SCRIPT_DIR/$file"
    if [ -f "$src" ]; then
        cp "$src" "$INSTALL_DIR/"
    else
        echo "[WARNING] Không tìm thấy $file"
    fi
done
echo "   Done"
echo ""

# Start server
echo "-> Khởi động server..."
echo ""
cd "$INSTALL_DIR"
echo "================================================"
echo "  Mở browser: http://localhost:3456"
echo "  Nhấn Ctrl+C để dừng"
echo "================================================"
echo ""
node server.js
