# Phase 3 — AI Content Creation Engine
## Weeks 5–7 | Complete in order. Commit after each section.

---

## STEP 3.0 — AI Service Base

### `app/Services/AI/BaseAIService.php`
```php
abstract class BaseAIService {
    protected function callGemini(string $prompt, array $options = []): string
    // POST https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent
    // Rate limit tracking: cache 'gemini_daily_calls' counter, max 1500/day
    // On rate limit: throw RateLimitException, fallback to Cloudflare Workers AI

    protected function trackUsage(string $service, int $tokens = 1): void
    // Stores daily usage in Redis: ai_usage:{service}:{date}
    // Used by dashboard usage widget
}
```

### `app/Services/AI/UsageTracker.php`
```php
// Track daily API usage per service
// Keys: gemini_calls, huggingface_calls, replicate_calls
// Alert when approaching limits (80% threshold)
public function getUsage(string $service, ?Carbon $date = null): int
public function increment(string $service): void
public function isNearLimit(string $service): bool
public function getDailyReport(): array
```

---

## STEP 3.1 — AI Caption Generator

### `app/Services/AI/CaptionGeneratorService.php`
```php
public function generate(array $params): array
// Returns 3 variations

// $params:
// - topic: string
// - platform: Platform enum
// - tone: string (professional|casual|funny|inspirational|educational|salesy)
// - length: string (short|medium|long)
// - includeHashtags: bool
// - includeCTA: bool
// - brandVoice: string (from BrandKit)
// - imageDescription: string (if image uploaded)

private function buildPrompt(array $params): string
// Builds structured Gemini prompt with:
// - Platform context (Twitter = punchy/short, LinkedIn = formal/longer)
// - Tone instruction
// - Brand voice from kit
// - Output format: return JSON array of 3 variations

public function generateFromImage(MediaFile $media, string $platform): array
// Sends base64 image to Gemini Vision API
// Returns caption suggestions based on image content

public function scoreHashtags(array $hashtags): array
// Returns ['#tag' => score_out_of_10, ...]
// Uses Gemini to evaluate relevance and popularity
```

### Livewire Component: `AI\CaptionGenerator`

UI (appears as a panel/modal triggered from composer):
```
┌─────────────────────────────────────────┐
│ 🤖 AI Caption Generator                 │
├─────────────────────────────────────────┤
│ Topic/Keywords: [___________________]   │
│ Platform: [Instagram ▼]                 │
│ Tone: [Casual ▼]  Length: [Medium ▼]    │
│ [✓] Include Hashtags  [✓] Add CTA       │
│                   [Generate ✨]          │
├─────────────────────────────────────────┤
│ Variation 1: "Your caption here..."     │
│                    [Use This] [Refine]  │
│ Variation 2: "Another option..."        │
│                    [Use This] [Refine]  │
│ Variation 3: "Third option..."          │
│                    [Use This] [Refine]  │
└─────────────────────────────────────────┘
```

- "Use This" → inserts into composer caption field
- "Refine" → opens inline text prompt to ask for modifications

---

## STEP 3.2 — Content Repurposing Engine

### `app/Services/AI/RepurposingService.php`
```php
public function linkedinToTwitterThread(string $article): array  // returns array of tweets
public function twitterThreadToInstagramCarousel(array $tweets): array  // returns array of slide texts
public function blogPostToSocialPost(string $blogContent, Platform $platform): string
public function expandTweetToLinkedIn(string $tweet): string
public function reformatForPlatform(string $content, Platform $from, Platform $to): string
```

### Livewire Component: `AI\ContentRepurposer`

Route: `GET /ai/repurpose`

UI:
- Input: large textarea "Paste your content here"
- Source type selector: Blog Post | LinkedIn Article | Twitter Thread | RSS Article
- Target platform selector
- "Repurpose →" button
- Output section: formatted result with "Open in Composer" button

---

## STEP 3.3 — AI Image Generator

### `app/Services/AI/ImageGeneratorService.php`
```php
public function generate(array $params): array  // returns array of MediaFile records

// Primary: Hugging Face Inference API — FLUX.1-schnell
private function callHuggingFace(string $prompt, array $options): string  // returns base64

// Backup: Stable Diffusion XL
private function callSDXL(string $prompt, array $options): string

// Fallback: Stability AI
private function callStabilityAI(string $prompt): string

public function enhancePrompt(string $roughPrompt): string
// Sends to Gemini: "Improve this image generation prompt for [style]: {prompt}"

private function buildPrompt(array $params): string
// Injects brand colors from BrandKit
// Adds style modifiers per preset (photorealistic, illustration, etc.)

private function addWatermark(string $imagePath, BrandKit $brandKit): string
// Uses Intervention Image to overlay logo at configured position
```

### Livewire Component: `AI\ImageGenerator`

Route: `GET /ai/images`

UI:
```
┌──────────────────────────────────────────────────────┐
│ 🎨 AI Image Generator                                 │
├──────────────────────────────────────────────────────┤
│ Prompt: [_______________________________________]     │
│         [✨ Enhance Prompt]                           │
│                                                      │
│ Style: [Photorealistic][Illustration][3D Render]     │
│        [Minimalist][Cinematic][Flat Design]          │
│                                                      │
│ Ratio: [1:1 Instagram][16:9 Twitter][9:16 Stories]   │
│        [2:3 Pinterest]                               │
│                                                      │
│ [✓] Apply Brand Colors  [✓] Add Watermark            │
│ Generate: [3 images ▼]         [Generate ✨]          │
├──────────────────────────────────────────────────────┤
│ [Image 1] [Image 2] [Image 3]  (grid)                │
│ Each with: [Use in Post] [Save to Library] [Discard] │
└──────────────────────────────────────────────────────┘
```

---

## STEP 3.4 — AI Video Generator

### `app/Services/AI/VideoGeneratorService.php`
```php
// Uses Replicate API
public function generateFromText(string $prompt, string $platform): MediaFile
// Model: zeroscope_v2_xl for 5-15 second clips

public function animateImage(MediaFile $image, string $motionPrompt): MediaFile
// Model: stable-video-diffusion

public function burnCaptions(MediaFile $video, string $text): MediaFile
// FFmpeg: overlay SRT subtitles burned into video

public function addBackgroundMusic(MediaFile $video, string $musicTrack): MediaFile
// FFmpeg: mix audio tracks

public function addIntroOutro(MediaFile $video, string $template): MediaFile
// FFmpeg: concatenate intro + video + outro clips

public function exportForPlatform(MediaFile $video, Platform $platform): MediaFile
// FFmpeg: resize + reformat
// Instagram Reels: 9:16, max 90s
// YouTube: 16:9
// TikTok: 9:16, max 60s
```

Royalty-free music library: store 10-20 MP3 files in `storage/app/music/`.

### Livewire Component: `AI\VideoGenerator`

Route: `GET /ai/video`

UI: Similar to image generator but with:
- Video prompt input
- OR "Animate an Image" tab (upload still image)
- Platform format selector
- Background music selector (dropdown of tracks)
- Intro/Outro toggle
- Caption/subtitle input (burned in)
- Progress bar (Replicate jobs take 30-120 seconds)
- Real-time status via Livewire polling or Reverb websocket

---

## STEP 3.5 — AI Content Strategy Engine

### `app/Services/AI/ContentStrategyService.php`
```php
public function getBestPostTimes(SocialAccount $account): array
// Queries analytics_snapshots, groups by hour, returns top 3

public function getContentTypeRecommendations(SocialAccount $account): array
// Compares engagement by media type from post history

public function getTrendingHashtags(string $niche): array
// Calls Gemini API: "What are the top 20 trending hashtags for {niche} on social media today?"
// Cached daily in Redis: trending_hashtags:{niche}

public function generateWeeklyPlan(string $topic, array $platforms): array
// Returns 7-day plan: [{date, platform, content_type, suggested_caption, hashtags}]
// Creates Content + Post records with status=needs_review

public function detectEvergreenContent(User $user): Collection
// Queries posts with highest engagement, flags for reposting

public function detectContentGaps(User $user): array
// Returns dates with no scheduled content in next 14 days

public function getNicheTrendAlerts(string $niche): array
// Polls RSS feeds + Twitter trending for niche keywords
```

### Livewire Component: `AI\StrategyDashboard`

Route: `GET /ai/strategy`

UI sections:
1. **Best Times to Post** — per platform horizontal bar chart (Chart.js)
2. **Weekly Plan Generator** — topic input → 7-day calendar grid populated with AI suggestions
3. **Trending Hashtags** — niche input → tag cloud with relevance scores
4. **Content Gaps** — calendar heatmap showing empty days (red) vs filled days (green)
5. **Evergreen Posts** — top performing posts with "Re-post" button

---

## STEP 3.6 — AI Auto-Distribution Mode

### Model: `AutomationRule` (already in schema)

### Livewire Component: `AI\AutoDistribution`

Route: `GET /ai/auto-distribute`

UI:
```
┌────────────────────────────────────────────────┐
│ 🤖 Auto-Distribution                           │
│                                [Master Pause ⏸] │
├────────────────────────────────────────────────┤
│ For each connected platform:                   │
│                                                │
│ [Instagram] ─────────────────────────────────  │
│   Theme/Niche: [Motivational quotes     ]      │
│   Frequency:  [2 posts per day ▼]              │
│   Mode: ○ Needs Review (safe)  ○ Auto-post     │
│   Status: [Active ●] [Pause] [Edit]            │
│                                                │
│ [LinkedIn] ─────────────────────────────────── │
│   Theme/Niche: [Tech tips & industry news ]    │
│   Frequency:  [1 post per day ▼]              │
│   Mode: ○ Needs Review (safe)  ● Auto-post     │
│   Status: [Active ●] [Pause] [Edit]            │
└────────────────────────────────────────────────┘
```

### Command: `ai:auto-distribute` (runs hourly)
```php
// For each active AutomationRule:
// 1. Check if it's time to generate a new post (based on frequency)
// 2. Call CaptionGeneratorService with rule's theme
// 3. Optionally call ImageGeneratorService
// 4. Create Content + Post record
// 5. If auto_post = false: status = needs_review
// 6. If auto_post = true: status = scheduled at best next time
```

---

## STEP 3.7 — AI Usage Dashboard Widget

Add to Dashboard or a settings page:

Show daily API usage progress bars:
- Gemini API: X / 1,500 requests (green → amber → red)
- Hugging Face: X calls today
- Replicate: X videos generated this month
- Stability AI: X / 25 credits

Redis keys: `ai_usage:gemini:{Y-m-d}`, `ai_usage:huggingface:{Y-m-d}`, etc.

---

## COMPLETION CHECKLIST
- [ ] BaseAIService with Gemini rate limiting + fallback
- [ ] UsageTracker with Redis + daily limits
- [ ] CaptionGeneratorService (3 variations, image-to-caption, hashtag scoring)
- [ ] CaptionGenerator Livewire UI working
- [ ] RepurposingService (all 5 methods)
- [ ] ContentRepurposer UI working
- [ ] ImageGeneratorService (HuggingFace + SDXL + Stability fallback)
- [ ] ImageGenerator UI with style presets + batch generation
- [ ] VideoGeneratorService (Replicate + FFmpeg)
- [ ] VideoGenerator UI with progress tracking
- [ ] ContentStrategyService (best times, weekly plan, trending hashtags, gaps)
- [ ] StrategyDashboard UI with charts
- [ ] AutoDistribution Livewire component
- [ ] ai:auto-distribute command working
- [ ] AI usage dashboard widget

When done: update `docs/current_phase.txt` to `4`, commit `feat(phase3): complete AI content creation engine`, stop.
