#!/bin/bash

# AirwavePBX Frontend Build Troubleshooting Script
# This script diagnoses and fixes frontend build issues during installation

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

# AirwavePBX paths
AIRWAVE_DIR="/opt/airwavepbx"
FRONTEND_DIR="${AIRWAVE_DIR}/frontend"
DIST_DIR="${FRONTEND_DIR}/dist"

echo -e "${BLUE}=== AirwavePBX Frontend Build Troubleshooting ===${NC}"
echo -e "${BLUE}Version: 1.0.4${NC}"
echo ""

# Function to check if running as root
check_root() {
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RED}This script must be run as root (use sudo)${NC}"
        exit 1
    fi
}

# Function to print status
print_status() {
    if [ $1 -eq 0 ]; then
        echo -e "${GREEN}✓${NC} $2"
    else
        echo -e "${RED}✗${NC} $2"
    fi
}

# Check if running as root
check_root

echo -e "${YELLOW}1. Checking directory structure...${NC}"
if [ -d "$AIRWAVE_DIR" ]; then
    print_status 0 "AirwavePBX directory exists: $AIRWAVE_DIR"
    ls -la "$AIRWAVE_DIR" | head -10
else
    print_status 1 "AirwavePBX directory NOT found: $AIRWAVE_DIR"
    exit 1
fi

echo ""
if [ -d "$FRONTEND_DIR" ]; then
    print_status 0 "Frontend directory exists: $FRONTEND_DIR"
    echo "   Contents:"
    ls -la "$FRONTEND_DIR" | head -10
else
    print_status 1 "Frontend directory NOT found: $FRONTEND_DIR"
    exit 1
fi

echo ""
echo -e "${YELLOW}2. Checking for dist directory...${NC}"
if [ -d "$DIST_DIR" ]; then
    print_status 0 "Dist directory exists: $DIST_DIR"
    echo "   Contents:"
    ls -la "$DIST_DIR" | head -10
else
    print_status 1 "Dist directory NOT found: $DIST_DIR"
fi

echo ""
echo -e "${YELLOW}3. Checking for node_modules...${NC}"
if [ -d "${FRONTEND_DIR}/node_modules" ]; then
    print_status 0 "node_modules exists in frontend directory"
    NODE_COUNT=$(find "${FRONTEND_DIR}/node_modules" -maxdepth 1 -type d | wc -l)
    echo "   Number of packages: $((NODE_COUNT - 1))"
else
    print_status 1 "node_modules NOT found in frontend directory"
fi

echo ""
echo -e "${YELLOW}4. Checking for package.json...${NC}"
if [ -f "${FRONTEND_DIR}/package.json" ]; then
    print_status 0 "package.json exists"
    echo "   Build script:"
    grep -A1 -B1 '"build"' "${FRONTEND_DIR}/package.json" || echo "   No build script found"
else
    print_status 1 "package.json NOT found"
fi

echo ""
echo -e "${YELLOW}5. Checking for npm/node installation...${NC}"
if command -v node &> /dev/null; then
    NODE_VERSION=$(node --version)
    print_status 0 "Node.js installed: $NODE_VERSION"
else
    print_status 1 "Node.js NOT installed"
fi

if command -v npm &> /dev/null; then
    NPM_VERSION=$(npm --version)
    print_status 0 "npm installed: $NPM_VERSION"
else
    print_status 1 "npm NOT installed"
fi

echo ""
echo -e "${YELLOW}6. Checking for build logs...${NC}"
LOG_DIR="/var/log/airwavepbx"
if [ -d "$LOG_DIR" ]; then
    echo "Looking for build-related errors in logs..."
    grep -i "npm\|node\|build\|frontend" "$LOG_DIR"/*.log 2>/dev/null | tail -20 || echo "   No build-related logs found"
fi

echo ""
echo -e "${YELLOW}7. Attempting to manually build frontend...${NC}"
read -p "Do you want to attempt a manual frontend build? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    cd "$FRONTEND_DIR"
    
    # Check if we need to install dependencies
    if [ ! -d "node_modules" ]; then
        echo -e "${BLUE}Installing npm dependencies...${NC}"
        npm install 2>&1 | tee /tmp/airwave-npm-install.log
        if [ ${PIPESTATUS[0]} -ne 0 ]; then
            echo -e "${RED}npm install failed! Check /tmp/airwave-npm-install.log${NC}"
            exit 1
        fi
    fi
    
    # Attempt to build
    echo -e "${BLUE}Running npm build...${NC}"
    npm run build 2>&1 | tee /tmp/airwave-npm-build.log
    if [ ${PIPESTATUS[0]} -ne 0 ]; then
        echo -e "${RED}npm build failed! Check /tmp/airwave-npm-build.log${NC}"
        echo ""
        echo "Last 50 lines of build log:"
        tail -50 /tmp/airwave-npm-build.log
        exit 1
    else
        echo -e "${GREEN}Build completed successfully!${NC}"
    fi
    
    # Verify dist was created
    if [ -d "$DIST_DIR" ]; then
        print_status 0 "Dist directory created successfully"
        echo "   Contents:"
        ls -la "$DIST_DIR" | head -10
    else
        print_status 1 "Dist directory still not found after build"
    fi
fi

echo ""
echo -e "${YELLOW}8. Checking file permissions...${NC}"
echo "Frontend directory permissions:"
ls -ld "$FRONTEND_DIR"
echo "Owner info:"
stat -c "Owner: %U:%G" "$FRONTEND_DIR"

echo ""
echo -e "${YELLOW}9. System resource check...${NC}"
echo "Disk space:"
df -h "$AIRWAVE_DIR"
echo ""
echo "Memory:"
free -h

echo ""
echo -e "${BLUE}=== Troubleshooting Summary ===${NC}"
echo ""
echo "Common issues and solutions:"
echo "1. If node_modules is missing: Run 'cd $FRONTEND_DIR && npm install'"
echo "2. If build fails with memory error: Increase system memory or add swap"
echo "3. If permissions error: Run 'chown -R airwavepbx:airwavepbx $FRONTEND_DIR'"
echo "4. If dist exists now: Re-run the installer verification"
echo ""
echo "Log files saved to:"
echo "  - /tmp/airwave-npm-install.log (if npm install was run)"
echo "  - /tmp/airwave-npm-build.log (if npm build was run)"
echo ""
echo -e "${GREEN}Script completed.${NC}"