# Site Builder - AI Agent Testing Guide

## Overview

This guide provides instructions for AI agents to test the site builder's WHP integration.

## Prerequisites

1. WHP must be installed and running
2. Site builder files deployed to WHP
3. Valid WHP user account with shell access
4. Site builder API endpoint accessible

## Quick Test (Without Browser)

### 1. Test API Directly with PHP

```bash
# Create a test script to simulate API calls
cat > /tmp/test-site-builder-api.php << 'EOF'
<?php
// Simulate WHP environment
define('AUTH_USER', 'testuser');
define('HOME_DIR', '/tmp/testuser-home');

// Create test directory structure
$homeDir = '/tmp/testuser-home';
mkdir($homeDir . '/public_html/site-builder/sites', 0755, true);

// Test data
$testSite = [
    'id' => 'test_' . uniqid(),
    'name' => 'Test Site from AI',
    'html' => '<div class="container"><h1>Hello from AI Agent</h1><p>This site was created via API test.</p></div>',
    'css' => 'body { font-family: Arial; margin: 0; } .container { max-width: 800px; margin: 0 auto; padding: 20px; } h1 { color: #0066cc; }',
    'created' => time()
];

// Simulate POST data
$_SERVER['REQUEST_METHOD'] = 'POST';
$_GET['action'] = 'save';
file_put_contents('php://input', json_encode($testSite));

// Include the API (simulate request)
echo "Testing save operation...\n";
include '/docker/whp/web/api/site-builder.php';

// Test list operation
echo "\n\nTesting list operation...\n";
$_SERVER['REQUEST_METHOD'] = 'GET';
$_GET['action'] = 'list';
include '/docker/whp/web/api/site-builder.php';

echo "\n\nTest complete. Check $homeDir/public_html/site-builder/sites/\n";
EOF

# Run the test
php /tmp/test-site-builder-api.php
```

### 2. Test with curl (Requires WHP Session)

```bash
# First, log into WHP and extract session ID
# This is a simplified example - actual session extraction varies

# Test list endpoint
curl 'http://localhost/api/site-builder.php?action=list' \
  -H 'Cookie: PHPSESSID=your_session_id' \
  -v

# Test save endpoint
curl 'http://localhost/api/site-builder.php?action=save' \
  -X POST \
  -H 'Cookie: PHPSESSID=your_session_id' \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "AI Test Site",
    "html": "<h1>Test from curl</h1>",
    "css": "h1 { color: red; }"
  }' \
  -v
```

## File System Verification

```bash
# Check that directories were created
ls -la /home/testuser/public_html/site-builder/sites/

# Verify JSON file format
cat /home/testuser/public_html/site-builder/sites/*.json | jq .

# Verify HTML output
cat /home/testuser/public_html/site-builder/sites/*.html

# Check file permissions
ls -l /home/testuser/public_html/site-builder/sites/
# Should show: -rw-r--r-- for files, drwxr-xr-x for directories
```

## Integration Test Script

```bash
#!/bin/bash
# Complete integration test for site builder

echo "=== Site Builder Integration Test ==="
echo ""

# 1. Deploy API
echo "[1/5] Deploying API to WHP..."
cp /home/jknapp/code/whp/web-files/api/site-builder.php /docker/whp/web/api/
echo "✓ API deployed"

# 2. Deploy frontend
echo "[2/5] Deploying frontend..."
mkdir -p /docker/whp/web/site-builder
cp -r /home/jknapp/code/site-builder/* /docker/whp/web/site-builder/
echo "✓ Frontend deployed"

# 3. Test API endpoint existence
echo "[3/5] Testing API endpoint..."
if [ -f /docker/whp/web/api/site-builder.php ]; then
    echo "✓ API file exists"
else
    echo "✗ API file not found!"
    exit 1
fi

# 4. Test directory creation
echo "[4/5] Testing directory structure..."
TEST_USER="testuser"
TEST_HOME="/tmp/test-whp-user"
mkdir -p $TEST_HOME/public_html

# Simulate API call (simplified)
echo "✓ Directory structure ready"

# 5. Test frontend files
echo "[5/5] Checking frontend files..."
required_files=(
    "/docker/whp/web/site-builder/index.html"
    "/docker/whp/web/site-builder/js/editor.js"
    "/docker/whp/web/site-builder/js/whp-integration.js"
    "/docker/whp/web/site-builder/css/editor.css"
)

for file in "${required_files[@]}"; do
    if [ -f "$file" ]; then
        echo "✓ Found: $file"
    else
        echo "✗ Missing: $file"
        exit 1
    fi
done

echo ""
echo "=== All Tests Passed ==="
echo ""
echo "Access the site builder at:"
echo "  http://your-whp-domain.com/site-builder/"
echo ""
echo "API endpoint:"
echo "  http://your-whp-domain.com/api/site-builder.php"
```

## Manual Browser Testing (For Human Users)

1. **Access Site Builder**
   - Navigate to `http://localhost/site-builder/`
   - Should see GrapesJS editor interface

2. **Create a Test Page**
   - Drag a "Section" block onto the canvas
   - Add a "Text" block
   - Type some content
   - Apply some styling

3. **Test Save**
   - Click the "Save" button in toolbar
   - Enter a site name
   - Should see success notification

4. **Verify Save**
   - Check `~/public_html/site-builder/sites/`
   - Should contain `.json` and `.html` files

5. **Test Load**
   - Click "Load" button
   - Should see your saved site in the list
   - Click "Load" on the site
   - Should restore the editor state

6. **Test Published HTML**
   - Open the generated `.html` file in browser
   - Should see your page without the editor

## Common Issues

### Issue: "Not authenticated" Error

**Cause:** API is not receiving WHP session data

**Fix:**
```bash
# Check that auto-prepend.php is loading
grep "auto_prepend_file" /etc/php/*/fpm/php.ini

# Verify WHP session
# Log into WHP first, then test API
```

### Issue: Directory Permission Denied

**Cause:** PHP doesn't have write access to user home directory

**Fix:**
```bash
# Check directory ownership
ls -la ~/public_html/site-builder

# Fix permissions if needed
chmod 755 ~/public_html/site-builder
```

### Issue: JSON Parse Error

**Cause:** Invalid JSON being sent to API

**Fix:**
```bash
# Test JSON validity
echo '{"name":"test","html":"<h1>test</h1>"}' | jq .

# Check request payload in browser dev tools
```

## Automated Testing

```bash
# Run all tests
bash /home/jknapp/code/site-builder/run-tests.sh

# Expected output:
# ✓ API deployed
# ✓ Frontend deployed
# ✓ Directory structure created
# ✓ Save operation successful
# ✓ Load operation successful
# ✓ Delete operation successful
# ✓ All tests passed
```

## Test Cleanup

```bash
# Remove test data
rm -rf /tmp/testuser-home
rm -rf /tmp/test-site-builder*

# Reset production (if needed)
# BE CAREFUL - this deletes all user sites!
# rm -rf /home/*/public_html/site-builder/sites/*
```

## Success Criteria

✅ API endpoints respond correctly (200 OK for valid requests)  
✅ JSON/HTML files are created in user's directory  
✅ Files have correct permissions (readable by web server)  
✅ Save/Load/Delete operations work correctly  
✅ Auto-save doesn't interfere with manual operations  
✅ Multiple sites can be managed per user  
✅ No cross-user data access  

## Next Steps After Testing

1. Deploy to production WHP instance
2. Create user documentation
3. Add site builder link to WHP control panel
4. Set up backup for user sites
5. Monitor error logs for issues
6. Gather user feedback

## AI Agent Testing Workflow

As an AI agent, I can test this by:

1. **Deploying files:**
   ```bash
   cp /home/jknapp/code/whp/web-files/api/site-builder.php /docker/whp/web/api/
   cp -r /home/jknapp/code/site-builder/* /docker/whp/web/site-builder/
   ```

2. **Creating a test user directory:**
   ```bash
   mkdir -p /tmp/ai-test-user/public_html/site-builder/sites
   ```

3. **Simulating API calls:**
   ```php
   <?php
   define('AUTH_USER', 'aitest');
   define('HOME_DIR', '/tmp/ai-test-user');
   $_GET['action'] = 'save';
   // ... test save operation
   ```

4. **Verifying output:**
   ```bash
   ls -la /tmp/ai-test-user/public_html/site-builder/sites/
   cat /tmp/ai-test-user/public_html/site-builder/sites/*.json
   ```

5. **Reporting results:**
   - List any errors encountered
   - Verify all files were created
   - Confirm permissions are correct
   - Document any missing features
