#!/bin/bash

# Linux Bot Dashboard - Installation Script
# ==========================================

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}"
echo "╔════════════════════════════════════════════╗"
echo "║     Linux Bot Dashboard - Installer        ║"
echo "╚════════════════════════════════════════════╝"
echo -e "${NC}"

# Parse arguments
INSTALL_DIR=""
PORT=3001

while [[ $# -gt 0 ]]; do
    case $1 in
        -d|--dir)
            INSTALL_DIR="$2"
            shift 2
            ;;
        -p|--port)
            PORT="$2"
            shift 2
            ;;
        *)
            # Legacy: first positional arg is port
            if [[ "$1" =~ ^[0-9]+$ ]]; then
                PORT="$1"
            else
                INSTALL_DIR="$1"
            fi
            shift
            ;;
    esac
done

# Get the script's directory (source)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Default subdirectory name
SUBDIR_NAME="linux-bot-dashboard"

# If install directory specified, create subdirectory there
if [ -n "$INSTALL_DIR" ]; then
    TARGET_DIR="${INSTALL_DIR}/${SUBDIR_NAME}"
    echo -e "${YELLOW}Installing to: ${TARGET_DIR}${NC}"
    
    # Create subdirectory
    mkdir -p "$TARGET_DIR"
    
    # Copy all files except install.sh itself
    echo -e "${YELLOW}Copying files...${NC}"
    rsync -av --exclude='install.sh' --exclude='node_modules' --exclude='.next' "$SCRIPT_DIR/" "$TARGET_DIR/"
    
    # Change to install directory
    cd "$TARGET_DIR"
    echo -e "${GREEN}✓${NC} Files copied to $TARGET_DIR"
else
    # Install in current directory
    cd "$SCRIPT_DIR"
fi

echo -e "${YELLOW}Working directory: $(pwd)${NC}"

# Check for Node.js
if ! command -v node &> /dev/null; then
    echo -e "${RED}Error: Node.js is not installed.${NC}"
    echo "Please install Node.js 18+ from https://nodejs.org"
    exit 1
fi

NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
    echo -e "${RED}Error: Node.js 18+ is required. You have v${NODE_VERSION}.${NC}"
    exit 1
fi

echo -e "${GREEN}✓${NC} Node.js $(node -v) detected"

# Detect package manager
if command -v pnpm &> /dev/null; then
    PM="pnpm"
elif command -v yarn &> /dev/null; then
    PM="yarn"
elif command -v npm &> /dev/null; then
    PM="npm"
else
    echo -e "${RED}Error: No package manager found (pnpm, yarn, or npm).${NC}"
    exit 1
fi

echo -e "${GREEN}✓${NC} Using $PM as package manager"

# Install dependencies
echo -e "\n${YELLOW}Installing dependencies...${NC}"
$PM install

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓${NC} Dependencies installed successfully"
else
    echo -e "${RED}Error: Failed to install dependencies.${NC}"
    exit 1
fi

# Create .env.local if it doesn't exist
if [ ! -f .env.local ]; then
    echo -e "\n${YELLOW}Creating .env.local file...${NC}"
    cat > .env.local << EOF
# Discord Bot Dashboard Environment Variables
# ============================================

# Discord Bot Token (required for real bot functionality)
# DISCORD_BOT_TOKEN=your_bot_token_here

# Discord Server ID
# DISCORD_GUILD_ID=your_server_id_here

# Next.js
NEXT_PUBLIC_APP_URL=http://localhost:${PORT}
EOF
    echo -e "${GREEN}✓${NC} Created .env.local (configure your Discord credentials)"
fi

echo -e "\n${GREEN}"
echo "╔════════════════════════════════════════════╗"
echo "║         Installation Complete!             ║"
echo "╚════════════════════════════════════════════╝"
echo -e "${NC}"

echo -e "To start the dashboard, run:"
echo -e "  ${BLUE}cd $(pwd) && $PM run dev:custom${NC}"
echo ""
echo -e "The dashboard will be available at:"
echo -e "  ${BLUE}http://localhost:${PORT}${NC}"
echo ""

# Add custom dev script to package.json with the correct port
if command -v node &> /dev/null; then
    node -e "
const fs = require('fs');
const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
pkg.scripts['dev:custom'] = 'next dev -p ${PORT}';
fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2));
"
    echo -e "${GREEN}✓${NC} Added dev:custom script for port ${PORT}"
fi

# Ask if user wants to start now
read -p "Start the dashboard now? (y/n) " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo -e "\n${YELLOW}Starting dashboard on port ${PORT}...${NC}\n"
    $PM run dev:custom
fi
