# Image Generation Feature - Testing Guide

## ✅ Implementation Complete

The AI-powered image generation feature has been fully implemented and is ready for testing.

---

## 🎯 What Was Implemented

### Backend (PHP)
1. **Database Tables**
   - `wp_wpaw_images` - Stores image recommendations from the agent
   - `wp_wpaw_images_variants` - Stores generated image variants

2. **Image Manager Class** (`includes/class-image-manager.php`)
   - Article analysis for optimal image placement
   - Model-specific prompt generation (FLUX.2 klein, Riverflow V2 Max, FLUX.2 max)
   - Image variant generation via OpenRouter API
   - WordPress Media Library integration
   - Automatic temp file cleanup (7+ days)

3. **REST API Endpoints**
   - `GET /wp-json/wp-agentic-writer/v1/image-recommendations/{post_id}`
   - `POST /wp-json/wp-agentic-writer/v1/generate-image`
   - `POST /wp-json/wp-agentic-writer/v1/commit-image`

4. **OpenRouter Provider Updates**
   - Proper image generation API implementation
   - Support for variant count, size, quality parameters

5. **Cron Job**
   - Daily cleanup of temp images older than 7 days
   - Automatic scheduling on plugin activation

### Frontend (JavaScript)
1. **Image Modal Component** (`assets/js/image-modal.js`)
   - Image recommendation review
   - Editable prompts and alt text
   - User-controlled variant count (1-3 per image)
   - Cost preview before generation
   - Variant selection interface
   - Automatic Gutenberg block updates

### Settings
1. **Updated Model Presets**
   - **Budget:** FLUX.2 klein ($0.014-0.042/image)
   - **Balanced:** Riverflow V2 Max ($0.03/image)
   - **Premium:** FLUX.2 max ($0.07-0.21/image)

---

## 🚀 How to Test

### Step 1: Activate/Reactivate Plugin

**Important:** You need to reactivate the plugin to create the new database tables.

1. Go to **Plugins** in WordPress admin
2. **Deactivate** WP Agentic Writer
3. **Activate** WP Agentic Writer again

This will:
- Create `wp_wpaw_images` table
- Create `wp_wpaw_images_variants` table
- Create `/wp-content/uploads/wpaw/` directory
- Schedule daily cleanup cron job

**Alternative:** Run the SQL manually in phpMyAdmin/Adminer using `CREATE_TABLE.sql`

### Step 2: Verify Tables Created

Run this in phpMyAdmin or Adminer:

```sql
SHOW TABLES LIKE 'wp_wpaw_%';
```

You should see:
- `wp_wpaw_cost_tracking`
- `wp_wpaw_images`
- `wp_wpaw_images_variants`

### Step 3: Configure Image Model

1. Go to **Settings → WP Agentic Writer**
2. Click **Models** tab
3. Choose a preset or manually select an image model:
   - Budget: `black-forest-labs/flux.2-klein`
   - Balanced: `sourceful/riverflow-v2-max` (recommended)
   - Premium: `black-forest-labs/flux.2-max`

### Step 4: Test Image Generation Flow

#### A. Create a New Post

1. Create a new post in WordPress
2. Open the **WP Agentic Writer** sidebar
3. Enable **Include Images** in the Config tab (should be on by default)

#### B. Generate Article with Images

1. In Chat mode, discuss your article topic
2. Switch to Planning mode
3. Click **Generate Plan**
4. Click **Execute Plan**

The agent will:
- Write the article content
- Insert `[IMAGE: description]` placeholders
- These will be converted to empty `core/image` blocks with `data-agent-image-id` attributes

#### C. Review Image Recommendations (Manual Trigger for Now)

**Note:** The automatic modal trigger after article generation needs to be integrated into `sidebar.js`. For now, you can test the backend directly:

**Test Backend API:**

```bash
# Get image recommendations
curl -X GET "http://your-site.local/wp-json/wp-agentic-writer/v1/image-recommendations/{POST_ID}" \
  -H "X-WP-Nonce: YOUR_NONCE"

# Generate image variants
curl -X POST "http://your-site.local/wp-json/wp-agentic-writer/v1/generate-image" \
  -H "Content-Type: application/json" \
  -H "X-WP-Nonce: YOUR_NONCE" \
  -d '{
    "post_id": 123,
    "agent_image_id": "img_hero_1",
    "prompt": "Modern dashboard interface with blue colors",
    "variant_count": 2
  }'

# Commit image to Media Library
curl -X POST "http://your-site.local/wp-json/wp-agentic-writer/v1/commit-image" \
  -H "Content-Type: application/json" \
  -H "X-WP-Nonce: YOUR_NONCE" \
  -d '{
    "post_id": 123,
    "agent_image_id": "img_hero_1",
    "variant_id": 1,
    "alt": "Dashboard showing workflow automation"
  }'
```

---

## 📁 File Structure

```
wp-agentic-writer/
├── includes/
│   ├── class-image-manager.php          ✅ NEW - Core image generation logic
│   ├── class-gutenberg-sidebar.php      ✅ UPDATED - Added REST endpoints
│   ├── class-openrouter-provider.php    ✅ UPDATED - Proper image API
│   └── class-settings.php               ✅ UPDATED - New image model presets
├── assets/
│   └── js/
│       └── image-modal.js               ✅ NEW - Frontend modal component
├── wp-agentic-writer.php                ✅ UPDATED - Activation & cron hooks
├── CREATE_TABLE.sql                     ✅ UPDATED - Added image tables
└── IMAGE_GENERATION_IMPLEMENTATION_PLAN.md  ✅ Complete implementation plan
```

---

## 🔍 Debugging

### Check if Tables Exist

```sql
DESCRIBE wp_wpaw_images;
DESCRIBE wp_wpaw_images_variants;
```

### Check Temp Directory

```bash
ls -la /path/to/wp-content/uploads/wpaw/
```

Should exist with `.htaccess` and `index.php` security files.

### Check Cron Job Scheduled

```php
// Add to functions.php temporarily
var_dump(wp_next_scheduled('wpaw_cleanup_temp_images'));
```

Should return a timestamp.

### Check REST API Endpoints

Visit: `http://your-site.local/wp-json/wp-agentic-writer/v1/`

Should list the new endpoints:
- `/image-recommendations/(?P<post_id>\d+)`
- `/generate-image`
- `/commit-image`

### Enable Debug Logging

Add to `wp-config.php`:

```php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
```

Check `/wp-content/debug.log` for errors.

---

## 💰 Cost Estimates

### Per Image (with 2 variants)

| Preset | Model | Cost per Image | Cost for 3 Images |
|--------|-------|----------------|-------------------|
| Budget | FLUX.2 klein | ~$0.04 | ~$0.12 |
| Balanced | Riverflow V2 Max | ~$0.06 | ~$0.18 |
| Premium | FLUX.2 max | ~$0.30 | ~$0.90 |

### User Controls

- **Variant count:** 1-3 per image (user selectable)
- **Image selection:** Generate only selected images
- **Skip option:** Can skip all images

---

## 🐛 Known Limitations

1. **Modal Integration:** The image modal needs to be triggered from `sidebar.js` after article execution completes. Currently, the modal component exists but needs integration.

2. **Image Block Detection:** The system looks for `core/image` blocks with `data-agent-image-id` attribute to update them after image selection.

3. **OpenRouter API:** Requires OpenRouter API key with image generation access. Not all models may be available depending on your OpenRouter account.

---

## 🔧 Next Steps for Full Integration

To complete the user-facing feature, you need to:

1. **Trigger Modal After Article Generation**
   - In `sidebar.js`, after article execution completes
   - Check if images were recommended
   - Open the image review modal

2. **Add "Generate Images" Button**
   - Add a button in the sidebar to manually trigger image generation
   - Useful for regenerating or adding images later

3. **Block Toolbar Integration**
   - Add "Generate Image" button to empty image blocks
   - Allow regeneration of existing images

---

## ✅ Testing Checklist

- [ ] Plugin reactivated successfully
- [ ] Database tables created
- [ ] Temp directory exists with security files
- [ ] Cron job scheduled
- [ ] Image model configured in settings
- [ ] Article generated with `[IMAGE: ...]` placeholders
- [ ] Image blocks created in Gutenberg
- [ ] REST API endpoints accessible
- [ ] Can generate image variants via API
- [ ] Can commit image to Media Library
- [ ] Temp files cleaned up after 7 days

---

## 📞 Support

If you encounter issues:

1. Check `wp-content/debug.log` for PHP errors
2. Check browser console for JavaScript errors
3. Verify OpenRouter API key has image generation access
4. Ensure database tables were created
5. Check file permissions on `/wp-content/uploads/wpaw/`

---

**Implementation Date:** January 28, 2026  
**Version:** 1.0  
**Status:** ✅ Ready for Testing
