# Optimizer Module

**Last Verified:** December 25, 2025  
**Status:** ⏸️ Inactive (Disabled by Default)  
**Backend Path:** `backend/igny8_core/modules/optimizer/` + `backend/igny8_core/business/optimization/`  
**Frontend Path:** `frontend/src/pages/Optimizer/`

---

## Module Status

| Aspect | Current State | Notes |
|--------|---------------|-------|
| Backend API | ✅ Implemented | Endpoints functional |
| Business Logic | ✅ Implemented | Optimization service exists |
| Frontend Pages | ✅ Implemented | UI exists |
| Sidebar Nav | ⚠️ Conditional | Hidden when disabled |
| Route Protection | ❌ Not Protected | Direct URL access still works |
| Dashboard References | ❌ Not Hidden | May show in dashboard |
| Default State | Disabled | `optimizer_enabled = True` in model, but typically disabled |

**⚠️ Pending Implementation:** Extend module disable to route-level protection and all page references.

---

## Quick Reference

| What | File | Key Items |
|------|------|-----------|
| Views | `modules/optimizer/views.py` | `OptimizerViewSet` |
| Models | `business/optimization/models.py` | `OptimizationTask` |
| Services | `business/optimization/services/*.py` | Optimization logic |
| AI Function | `ai/functions/optimize.py` | `OptimizeContentFunction` |
| Frontend Pages | `pages/Optimizer/index.tsx` | Optimizer overview |
| Frontend Pages | `pages/Optimizer/OptimizerContent.tsx` | Select content |
| Frontend Pages | `pages/Optimizer/OptimizerPreview.tsx` | Analysis preview |
| API Client | `api/optimizer.api.ts` | `optimizerApi` |
| Module Control | `modules/system/settings_models.py` | `ModuleEnableSettings.optimizer_enabled` |

---

## Purpose

The Optimizer module provides AI-powered content optimization:
- Analyze existing content for SEO improvements
- Suggest and apply optimizations
- Track before/after scores

---

## Data Models

### OptimizationTask

| Field | Type | Purpose |
|-------|------|---------|
| account | FK | Owner account |
| site | FK | Parent site |
| sector | FK | Parent sector |
| content | FK | Target content |
| entry_point | CharField | auto/igny8/wordpress/external/manual |
| status | CharField | pending/analyzing/optimizing/completed/failed |
| original_score | Integer | Score before optimization |
| optimized_score | Integer | Score after optimization |
| original_content | TextField | Content before changes |
| optimized_content | TextField | Content after changes |
| suggestions | JSON | Optimization suggestions |
| applied_changes | JSON | Changes that were applied |
| credits_used | Decimal | Credits consumed |
| created_at | DateTime | Creation date |
| completed_at | DateTime | Completion date |

---

## API Endpoints

| Method | Path | Handler | Purpose |
|--------|------|---------|---------|
| POST | `/api/v1/optimizer/optimize/` | `OptimizerViewSet.optimize` | Optimize single content |
| POST | `/api/v1/optimizer/batch_optimize/` | `OptimizerViewSet.batch_optimize` | Optimize multiple items |
| POST | `/api/v1/optimizer/analyze/` | `OptimizerViewSet.analyze` | Analyze without applying |

### Entry Points

| Entry Point | Description |
|-------------|-------------|
| `auto` | Auto-detect based on content source |
| `igny8` | IGNY8-generated content |
| `wordpress` | WordPress-synced content |
| `external` | External platform content |
| `manual` | Manual optimization trigger |

### Optimize Request

```json
{
  "content_id": 123,
  "entry_point": "igny8",
  "optimization_goals": ["seo", "readability", "keyword_density"]
}
```

### Optimize Response

```json
{
  "task_id": 456,
  "content_id": 123,
  "original_score": 65,
  "optimized_score": 85,
  "suggestions": [
    {
      "type": "keyword_density",
      "description": "Increase keyword 'SEO' usage",
      "applied": true
    },
    {
      "type": "meta_description",
      "description": "Meta description too short",
      "applied": true
    }
  ],
  "credits_used": 15
}
```

---

## Business Logic

### Content Analysis

**Trigger:** User clicks "Analyze"  
**Credit Cost:** None (analysis only)

**Checks:**
- Keyword density and distribution
- Meta title and description optimization
- Heading structure (H1, H2, H3)
- Readability score
- Content length
- Internal/external link count
- Image alt text presence

### Content Optimization (AI)

**Trigger:** User clicks "Optimize"  
**AI Function:** `OptimizeContentFunction`  
**Credit Cost:** Per 200 words

**Flow:**
1. Load content with metadata
2. Analyze current state
3. AIEngine executes `OptimizeContentFunction`:
   - Reviews content against SEO best practices
   - Suggests improvements
   - Rewrites sections if needed
4. Create `OptimizationTask` record
5. Save original and optimized versions
6. Return comparison view

---

## Module Enable Control

### Backend Model

```python
# modules/system/settings_models.py
class ModuleEnableSettings(AccountBaseModel):
    optimizer_enabled = models.BooleanField(default=True)
```

### Frontend Check

```typescript
// layout/AppSidebar.tsx
if (isModuleEnabled('optimizer')) {
  workflowItems.push({
    name: "Optimizer",
    path: "/optimizer/content",
  });
}
```

### Current Limitation

Direct URL access to `/optimizer/*` routes still works even when module is disabled.

---

## Frontend Pages

### Optimizer Overview (`/optimizer`)

- Module overview
- Quick stats
- Recent optimizations

### Select Content (`/optimizer/content`)

- List of content available for optimization
- Filter by score, status
- Start analysis button
- Batch optimize action

### Analysis Preview (`/optimizer/preview`)

- Side-by-side comparison
- Suggestion list
- Accept/reject changes
- Apply optimization button

---

## Optimization Scoring

| Metric | Weight | Description |
|--------|--------|-------------|
| Keyword Density | 20% | Target 1-3% density |
| Meta Quality | 15% | Title 50-60 chars, desc 150-160 chars |
| Heading Structure | 15% | Proper H1-H6 hierarchy |
| Readability | 15% | Flesch-Kincaid score |
| Content Length | 10% | Meets word count target |
| Internal Links | 10% | 2-5 internal links |
| Image Optimization | 10% | Alt text, sizing |
| Mobile Friendly | 5% | No wide elements |

---

## Integration Points

| From | To | Trigger |
|------|----|---------| 
| Content | Optimizer | Manual analysis/optimize |
| WordPress | Optimizer | Synced content optimization |
| Optimizer | Content | Apply changes |
| Automation | Optimizer | Automated optimization (future) |

---

## Common Issues

| Issue | Cause | Fix |
|-------|-------|-----|
| Module visible when disabled | Only sidebar hidden | Pending: route protection |
| Optimization not improving | Content already good | Check original score |
| High credit usage | Large content | Optimize sections |
| Changes not saving | Apply not clicked | Click "Apply Changes" |

---

## Planned Changes

| Feature | Status | Description |
|---------|--------|-------------|
| Route-level protection | 🔜 Pending | Block access when module disabled |
| Dashboard card hiding | 🔜 Pending | Hide from dashboard when disabled |
| Automation integration | 🔜 Planned | Add to automation pipeline |
| Partial optimization | 🔜 Planned | Optimize specific sections only |
| Competitor analysis | 🔜 Planned | Compare against top-ranking content |
| A/B testing | 🔜 Planned | Track performance of optimizations |
