#!/bin/bash

# BMAD Enhanced - Test Published Beta Version
# Downloads and tests the published beta version from NPM

set -e

# Load common validation functions
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common-validation.sh"

# Colors for output (also defined in common-validation.sh)
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo -e "${BLUE}🧪 BMAD Enhanced - Testing Published Beta${NC}"
echo "========================================="
echo ""

# Get the latest beta version from NPM
echo -e "${YELLOW}📦 Checking latest beta version on NPM...${NC}"
BETA_VERSION=$(npm view @cloudkinetix/bmad-enhanced@beta version 2>/dev/null || echo "none")

if [ "$BETA_VERSION" = "none" ]; then
    echo -e "${RED}❌ No beta version found on NPM${NC}"
    echo "Please publish a beta version first with: npm run publish:beta"
    exit 1
fi

echo -e "${GREEN}✅ Found beta version: $BETA_VERSION${NC}"
echo ""

# Base directory for this script's tests
BASE_DIR="test-results/05-test-published-beta"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
TEST_INSTANCE="$BASE_DIR/$TIMESTAMP"

# Clean up and create directories
echo -e "${YELLOW}🧹 Setting up test directories...${NC}"
mkdir -p "$TEST_INSTANCE"
echo "Test results will be saved in: $TEST_INSTANCE/"

# Test 1: Non-interactive installation with minimal setup
echo -e "${BLUE}📋 Test 1: Non-Interactive Installation (Minimal)${NC}"
echo "Testing: npx @cloudkinetix/bmad-enhanced@beta install --non-interactive --ide cursor"
echo ""

TEST_DIR="$TEST_INSTANCE/beta-validation-minimal"
rm -rf "$TEST_DIR"
mkdir -p "$TEST_DIR"

if npx @cloudkinetix/bmad-enhanced@beta install --non-interactive --ide cursor --directory "$TEST_DIR"; then
    echo -e "${GREEN}✅ Minimal installation successful${NC}"
    
    # Validate basic structure using common function
    if ! validate_basic_structure "$TEST_DIR"; then
        exit 1
    fi
else
    echo -e "${RED}❌ Default installation failed${NC}"
    exit 1
fi

echo ""

# Test 2: Full installation with all IDEs
echo -e "${BLUE}📋 Test 2: Full Installation with All IDEs${NC}"
echo "Testing: npx @cloudkinetix/bmad-enhanced@beta install --full"
echo ""

TEST_DIR="$TEST_INSTANCE/beta-validation-full"
rm -rf "$TEST_DIR"
mkdir -p "$TEST_DIR"

if npx @cloudkinetix/bmad-enhanced@beta install --full --non-interactive --directory "$TEST_DIR"; then
    echo -e "${GREEN}✅ Full installation successful${NC}"
    
    # Validate IDE installations using common function
    if ! validate_ide_installation "$TEST_DIR" 8; then
        exit 1
    fi
    
    # Check if KiloCode is installed (optional)
    check_kilocode_installation "$TEST_DIR"
    
    # Validate expansion packs
    echo ""
    echo -e "${YELLOW}Validating expansion packs...${NC}"
    
    # Check for CK expansion pack agents
    CK_AGENTS=("jira" "llm-wizard" "llm-architect" "llm-engineer" "llm-orchestrator" "llm-safety-governance" "glab" "parallel")
    MISSING_AGENTS=0
    
    for agent in "${CK_AGENTS[@]}"; do
        if ls "$TEST_DIR/.cursor/rules/"*"$agent"* 2>/dev/null | grep -q .; then
            echo -e "  ${GREEN}✓ $agent agent found${NC}"
        else
            echo -e "  ${RED}✗ Missing: $agent agent${NC}"
            MISSING_AGENTS=$((MISSING_AGENTS + 1))
        fi
    done
    
    if [ $MISSING_AGENTS -gt 0 ]; then
        echo -e "${YELLOW}⚠️  Warning: $MISSING_AGENTS CK agents missing${NC}"
    else
        echo -e "${GREEN}✅ All CK expansion pack agents found${NC}"
    fi
else
    echo -e "${RED}❌ Full installation failed${NC}"
    exit 1
fi

echo ""

# Test 3: Specific IDE installations
echo -e "${BLUE}📋 Test 3: Specific IDE Installation${NC}"
echo "Testing: npx @cloudkinetix/bmad-enhanced@beta install --ide cursor --expansion-packs ck-llm-agent-dev"
echo ""

TEST_DIR="$TEST_INSTANCE/beta-validation-cursor-llm"
rm -rf "$TEST_DIR"
mkdir -p "$TEST_DIR"

if npx @cloudkinetix/bmad-enhanced@beta install --ide cursor --expansion-packs ck-llm-agent-dev --non-interactive --directory "$TEST_DIR"; then
    echo -e "${GREEN}✅ Cursor + LLM Agent Dev installation successful${NC}"
    
    # Validate LLM agent integration
    if [ -f "$TEST_DIR/.cursor/rules/llm-architect.mdc" ]; then
        echo -e "${GREEN}✅ LLM agent integration validated${NC}"
    else
        echo -e "${RED}❌ LLM agent integration validation failed${NC}"
        exit 1
    fi
else
    echo -e "${RED}❌ Cursor + LLM Agent Dev installation failed${NC}"
    exit 1
fi

echo ""

# Test 4: Status command
echo -e "${BLUE}📋 Test 4: Status Command${NC}"
echo "Testing status command functionality..."
echo ""

cd "$TEST_DIR"
if npx @cloudkinetix/bmad-enhanced@beta status; then
    echo -e "${GREEN}✅ Status command works${NC}"
else
    echo -e "${RED}❌ Status command failed${NC}"
    exit 1
fi
cd - > /dev/null

echo ""

# Summary
echo -e "${BLUE}📊 Beta Testing Summary${NC}"
echo "======================="
echo -e "${GREEN}✅ Beta version $BETA_VERSION tested successfully!${NC}"
echo ""
echo "Tests completed:"
echo "  ✓ Default installation"
echo "  ✓ Full installation with all 8 IDEs"
echo "  ✓ Specific IDE with expansion pack"
echo "  ✓ Status command functionality"
echo ""
echo "Test results saved in: $TEST_INSTANCE/"
echo ""
echo -e "${YELLOW}Next steps:${NC}"
echo "1. Review the test results"
echo "2. If all looks good, publish stable with: npm run publish:stable"
echo "3. If issues found, fix and publish new beta"