# AI Image Generation Setup Guide

## Tổng quan
Hệ thống này tích hợp Google Imagen 3 để tự động tạo ảnh cho bài viết được sinh bởi Claude AI.

## Quy trình hoạt động

### Workflow tự động:
1. **Nhập thông tin** → User nhập title/description
2. **Generate structure** → Claude tạo SEO tags và cấu trúc
3. **Write article** → Claude viết bài với placeholder images
4. **Parse images** → Frontend tự động phân tích placeholder images
5. **Generate images** → Batch gửi job queue để tạo ảnh với Google AI
6. **Replace placeholders** → Polling để cập nhật ảnh real-time
7. **Save content** → User save bài viết hoàn chỉnh vào editor

## Setup Instructions

### 1. Environment Configuration
Thêm vào file `.env`:
```bash
# Google AI Configuration (required)
GOOGLE_AI_API_KEY=your_google_ai_api_key_here
GOOGLE_AI_IMAGE_MODEL=imagen-3.0-generate-001
GOOGLE_AI_TIMEOUT=120

# Image Generation Settings (affects cost and quality)
GOOGLE_AI_ASPECT_RATIO=ASPECT_RATIO_1_1
GOOGLE_AI_SAFETY_FILTER=FILTER_MEDIUM
GOOGLE_AI_PERSON_GENERATION=DONT_ALLOW

# Queue configuration (required)
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
```

### 1.1. Cấu hình kích thước ảnh (Quan trọng cho cost!)

**Aspect Ratio Options & Cost Impact:**
- `ASPECT_RATIO_1_1` = 1024x1024px (Square) - **Recommended** - Balanced cost/quality
- `ASPECT_RATIO_16_9` = 1536x864px (Landscape) - Higher cost, good for headers
- `ASPECT_RATIO_9_16` = 864x1536px (Portrait) - Higher cost, good for mobile
- `ASPECT_RATIO_4_3` = 1152x896px (Traditional landscape)
- `ASPECT_RATIO_3_4` = 896x1152px (Traditional portrait)

**Cost Breakdown (Google AI Studio pricing):**
- 1024x1024 (1:1): ~$0.040 per image
- 1536x864 (16:9): ~$0.065 per image  
- Larger sizes cost more due to higher token usage

**Recommendations:**
- **Development/Testing**: Use `ASPECT_RATIO_1_1` (cheapest)
- **Production Blog**: Use `ASPECT_RATIO_16_9` (better for articles)
- **Mobile Content**: Use `ASPECT_RATIO_9_16`

### 2. Lấy Google AI API Key
1. Truy cập: https://aistudio.google.com/app/apikey
2. Tạo API key mới
3. Copy và paste vào `.env`

### 3. Start Required Services
```bash
# Start Redis (required cho queue)
redis-server

# Start Queue Worker (required cho image generation)
php artisan queue:work --tries=3

# Start Development Server
composer dev
```

## Files đã được tạo/sửa

### Backend Files:
- `config/google.php` - Google AI configuration
- `app/Services/GoogleAiService.php` - Service xử lý Google AI API
- `app/Jobs/GenerateImageJob.php` - Job queue tạo ảnh async
- `app/Http/Controllers/ImageGenerationController.php` - API controller
- `app/Http/Controllers/ClaudeAiController.php` - Updated prompts
- `routes/web.php` - Added image generation routes

### Frontend Files:
- `resources/js/pages/admin/mattock/articles/Create.vue` - Updated với image processing

### Database:
- Migration `conversations` table đã có sẵn

## API Endpoints mới

```bash
POST /api/images/generate-batch
POST /api/images/check-status  
GET  /api/images/generated/{conversation_id}
```

## Cách sử dụng

### 1. Tạo bài viết với AI
1. Vào màn hình tạo bài viết `/admin/mattock/articles/create`
2. Click nút AI (icon brain)
3. Nhập title và description → Next
4. Review structure → Write Article
5. Chờ AI viết xong → Tự động tạo ảnh
6. Save content vào editor

### 2. Monitoring
- Queue jobs: `php artisan queue:monitor`
- Logs: `php artisan pail`
- Image generation logs trong Laravel logs

## Troubleshooting

### Lỗi thường gặp:

**1. Google AI API Error**
```bash
# Check API key
php artisan tinker
>>> app(\App\Services\GoogleAiService::class)->testConnection()
```

**2. Queue không chạy**
```bash
# Check Redis connection
redis-cli ping

# Restart queue worker
php artisan queue:restart
php artisan queue:work
```

**3. Images không hiển thị**
```bash
# Check storage link
php artisan storage:link

# Check permissions
chmod -R 755 storage/app/public/uploads/
```

**4. Memory/Timeout issues**
- Tăng `GOOGLE_AI_TIMEOUT` trong `.env`
- Check PHP memory limit
- Monitor queue job attempts

## Testing

### Manual Test:
1. Tạo bài viết test với AI assistant
2. Verify placeholder images xuất hiện trong step 3
3. Check queue jobs: `php artisan queue:monitor`
4. Verify images được replace khi hoàn thành

### Debug Mode:
```bash
# Check queue jobs
php artisan queue:failed

# Retry failed jobs  
php artisan queue:retry all

# Clear cache if needed
php artisan cache:clear
```

## Cost Management & Performance

### Cost Control Settings:
```bash
# Limit số ảnh tối đa mỗi bài viết (affects total cost)
GOOGLE_AI_MAX_IMAGES_PER_ARTICLE=5

# Default aspect ratio cho cost optimization
GOOGLE_AI_ASPECT_RATIO=ASPECT_RATIO_1_1

# Premium aspect ratio cho important articles
GOOGLE_AI_PREMIUM_ASPECT_RATIO=ASPECT_RATIO_16_9
```

### Cost Estimation:
- **1 bài viết (5 ảnh 1024x1024)**: ~$0.20 USD
- **1 bài viết (5 ảnh 1536x864)**: ~$0.325 USD  
- **1000 bài viết/tháng (1:1)**: ~$200 USD
- **1000 bài viết/tháng (16:9)**: ~$325 USD

### Performance Notes:
- **Rate limiting**: Google AI có rate limits, job sẽ retry tự động
- **Concurrent images**: Configurable limit (default 5 ảnh/batch)
- **Timeout**: Default 300s/job, max 10 phút polling
- **Storage**: Ảnh lưu tại `storage/app/public/uploads/ai-images/`
- **Cache**: Event data cache 5 phút cho polling

### Cost Optimization Tips:
1. **Development**: Sử dụng `ASPECT_RATIO_1_1` để tiết kiệm cost
2. **Production**: Cân nhắc giữa quality và cost
3. **Batch processing**: System tự động batch để tối ưu performance
4. **Retry logic**: Failed jobs sẽ retry tự động, không mất tiền
5. **Monitoring**: Track usage qua Laravel logs

## Security

- API routes yêu cầu authentication
- CSRF protection enabled
- Input validation cho prompts
- Safe image generation prompts only

## Quick Commands

### Cost Estimation (không cần API key):
```bash
php artisan ai:test-images --cost-only
```

### Full Test (cần API key):
```bash
php artisan ai:test-images
```

### Queue Monitoring:
```bash
php artisan queue:monitor
php artisan queue:failed
```

## Next Steps

Sau khi setup xong:
1. **Test Cost**: `php artisan ai:test-images --cost-only`
2. **Configure API Key**: Lấy từ Google AI Studio
3. **Test Connection**: `php artisan ai:test-images`
4. **Start Services**: Redis + Queue worker
5. **Create Test Article**: Dùng AI assistant trong admin
6. **Monitor Usage**: Check Laravel logs và queue
7. **Adjust Settings**: Optimize cost vs quality trong .env