#!/bin/bash

# Meilisearch Production Fix Script
# This script diagnoses and fixes common Meilisearch production issues

set -e

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo "=========================================="
echo "Meilisearch Production Diagnostic & Fix"
echo "=========================================="
echo ""

# Step 1: Check if Meilisearch service is running
echo -e "${YELLOW}Step 1: Checking Meilisearch service status...${NC}"
if systemctl is-active --quiet meilisearch 2>/dev/null; then
    echo -e "${GREEN}✓ Meilisearch service is running${NC}"
    systemctl status meilisearch --no-pager -l | head -10
else
    echo -e "${RED}✗ Meilisearch service is NOT running${NC}"
    echo "  Attempting to start..."
    sudo systemctl start meilisearch 2>/dev/null || echo "  Failed to start. Check service configuration."
fi

echo ""

# Step 2: Check if Meilisearch is listening on port 7700
echo -e "${YELLOW}Step 2: Checking if Meilisearch is listening on port 7700...${NC}"
if netstat -tlnp 2>/dev/null | grep -q ":7700" || ss -tlnp 2>/dev/null | grep -q ":7700"; then
    echo -e "${GREEN}✓ Port 7700 is listening${NC}"
    netstat -tlnp 2>/dev/null | grep ":7700" || ss -tlnp 2>/dev/null | grep ":7700"
else
    echo -e "${RED}✗ Port 7700 is NOT listening${NC}"
    echo "  Meilisearch may not be running or configured incorrectly"
fi

echo ""

# Step 3: Test Meilisearch health endpoint
echo -e "${YELLOW}Step 3: Testing Meilisearch health endpoint...${NC}"
HEALTH_RESPONSE=$(curl -s http://127.0.0.1:7700/health 2>&1 || echo "ERROR")
if echo "$HEALTH_RESPONSE" | grep -q "available"; then
    echo -e "${GREEN}✓ Meilisearch health check passed${NC}"
    echo "  Response: $HEALTH_RESPONSE"
else
    echo -e "${RED}✗ Meilisearch health check failed${NC}"
    echo "  Response: $HEALTH_RESPONSE"
    echo "  Meilisearch may not be accessible or not running"
fi

echo ""

# Step 4: Check environment variables for Next.js
echo -e "${YELLOW}Step 4: Checking Next.js environment variables...${NC}"
ENV_FILE=".env.production"
if [ ! -f "$ENV_FILE" ]; then
    ENV_FILE=".env.local"
fi

if [ -f "$ENV_FILE" ]; then
    echo "  Checking $ENV_FILE:"
    if grep -q "NEXT_PUBLIC_MEILISEARCH_HOST" "$ENV_FILE"; then
        MEILI_HOST=$(grep "NEXT_PUBLIC_MEILISEARCH_HOST" "$ENV_FILE" | cut -d '=' -f2 | tr -d '"' | tr -d "'")
        echo -e "  ${GREEN}✓ NEXT_PUBLIC_MEILISEARCH_HOST is set: $MEILI_HOST${NC}"
    else
        echo -e "  ${RED}✗ NEXT_PUBLIC_MEILISEARCH_HOST is NOT set${NC}"
        echo "  Add this to $ENV_FILE:"
        echo "  NEXT_PUBLIC_MEILISEARCH_HOST=http://127.0.0.1:7700"
    fi
    
    if grep -q "NEXT_PUBLIC_MEILISEARCH_SEARCH_KEY" "$ENV_FILE"; then
        echo -e "  ${GREEN}✓ NEXT_PUBLIC_MEILISEARCH_SEARCH_KEY is set${NC}"
    else
        echo -e "  ${YELLOW}⚠ NEXT_PUBLIC_MEILISEARCH_SEARCH_KEY is not set (optional)${NC}"
    fi
else
    echo -e "  ${RED}✗ Environment file ($ENV_FILE) not found${NC}"
    echo "  Create $ENV_FILE with:"
    echo "  NEXT_PUBLIC_MEILISEARCH_HOST=http://127.0.0.1:7700"
fi

echo ""

# Step 5: Check if Meilisearch index exists
echo -e "${YELLOW}Step 5: Checking if 'properties' index exists...${NC}"
if command -v curl >/dev/null 2>&1; then
    # Try to check index (this might require authentication)
    INDEX_CHECK=$(curl -s http://127.0.0.1:7700/indexes/properties 2>&1 || echo "ERROR")
    if echo "$INDEX_CHECK" | grep -q "uid\|name"; then
        echo -e "${GREEN}✓ 'properties' index exists${NC}"
    elif echo "$INDEX_CHECK" | grep -q "index_not_found\|404"; then
        echo -e "${RED}✗ 'properties' index NOT found${NC}"
        echo "  The index needs to be created by Strapi CMS"
        echo "  Restart Strapi to initialize the index"
    else
        echo -e "${YELLOW}⚠ Could not check index (may require authentication)${NC}"
    fi
else
    echo -e "${YELLOW}⚠ curl not available, skipping index check${NC}"
fi

echo ""

# Step 6: Check code configuration
echo -e "${YELLOW}Step 6: Checking code configuration...${NC}"
STRAPI_TS="src/utils/strapi.ts"
if [ -f "$STRAPI_TS" ]; then
    if grep -q "USE_MEILISEARCH.*=.*false" "$STRAPI_TS"; then
        echo -e "${YELLOW}⚠ Found hardcoded false value, checking for dynamic configuration...${NC}"
        if grep -q "process.env.ENABLE_MEILISEARCH\|process.env.NODE_ENV.*production" "$STRAPI_TS"; then
            echo -e "${GREEN}✓ Meilisearch is configured dynamically (enabled in production by default)${NC}"
            
            # Check environment variable
            if [ -f "$ENV_FILE" ] && grep -q "ENABLE_MEILISEARCH" "$ENV_FILE"; then
                ENABLE_VAL=$(grep "ENABLE_MEILISEARCH" "$ENV_FILE" | cut -d '=' -f2 | tr -d '"' | tr -d "'" | tr -d ' ')
                echo "  ENABLE_MEILISEARCH is set to: $ENABLE_VAL"
            else
                echo "  ENABLE_MEILISEARCH not set - will default to enabled in production"
            fi
        else
            echo -e "${RED}✗ Meilisearch appears to be hardcoded to false${NC}"
        fi
    else
        echo -e "${GREEN}✓ Meilisearch configuration found${NC}"
    fi
else
    echo -e "${YELLOW}⚠ Could not find $STRAPI_TS${NC}"
fi

echo ""

# Step 7: Summary and recommendations
echo "=========================================="
echo "Summary & Recommendations:"
echo "=========================================="
echo ""
echo "1. Verify Meilisearch service:"
echo "   sudo systemctl status meilisearch"
echo ""
echo "2. Check Meilisearch logs:"
echo "   sudo journalctl -u meilisearch -n 50"
echo ""
echo "3. Test Meilisearch directly:"
echo "   curl http://127.0.0.1:7700/health"
echo ""
echo "4. Ensure environment variables are set:"
echo "   - NEXT_PUBLIC_MEILISEARCH_HOST in .env.production or .env.local"
echo ""
echo "5. Meilisearch is now enabled automatically in production:"
echo "   - Enabled by default when NODE_ENV=production"
echo "   - Can be controlled via ENABLE_MEILISEARCH environment variable"
echo "   - No code changes needed"
echo ""
echo "6. Restart Next.js application after fixing:"
echo "   pm2 restart nrel-2025"
echo "   # or"
echo "   npm run build && npm start"
echo ""

