# AI Content Generation & Lead Intelligence (Task 021 Phase 2)

Extends the existing **AI Inbox Classification** system with content generation, segment building, lead scoring, and next-best-action — without duplicating inbox classification features.

## What already exists (unchanged)

- AI reply classification, intent, sentiment, temperature, confidence
- Suggested action, convert to lead, create task, stop sequence, suppression
- Inbox AI panel (`AiClassificationPanel`)

## Brand Voice

**Settings → AI → Brand Voice** (`/settings/ai`)

Stored on `SystemSetting.brandVoice`:

| Field | Purpose |
|-------|---------|
| companyName, companyDescription, services, targetAudience | Context for all generation |
| tone | professional, friendly, executive, direct, consultative |
| defaultCta, senderSignature, forbiddenClaims | Output constraints |
| preferredLanguage | ar, en, auto |

API: `GET/PATCH /api/settings/ai/brand-voice`

All AI generation injects brand voice via `buildBrandVoicePrompt()` — **never hardcodes company names**; uses `companyName`, `senderSignature`, `defaultCta`, etc. from settings only.

## Output language

All generation panels require **Language: Arabic | English**:

| Panel | Location |
|-------|----------|
| AI Email Writer | Templates, Campaigns |
| AI Template Generator | Email template builder |
| AI Sequence Generator | `/sequences/new` |

**Default:** resolved from Brand Voice `preferredLanguage` (`ar` → Arabic, `en` → English, `auto` → UI locale).

**Arabic (`ar`):** fully Arabic subject, body, CTA, greeting, closing; `dir="rtl"` on body HTML; no English phrases (Dear, Best regards, etc.). Variables preserved as-is.

**English (`en`):** fully English subject, body, CTA, greeting, closing; `dir="ltr"` on body HTML. Variables preserved as-is.

**Apply behavior:** clicking **حفظ كقالب (تطبيق)** or **تطبيق على المحرر** immediately updates subject, body, CTA buttons, template direction, and live preview in the template builder.

## AI Email Writer

**UI:** Templates, Campaigns, Sequence builder  
**API:** `POST /api/ai/email-writer`

Actions: generate, improve, rewrite, shorten, expand, more_professional, more_friendly, more_direct

Output: `{ subject, body, suggestedCta }` — user must review before save.

Variables only: `{{person_name}}`, `{{company_name}}`, `{{sector}}`, `{{city}}`, `{{recommended_service}}`, `{{sender_name}}`, `{{sender_email}}`

## AI Template Generator

**UI:** Email template builder  
**API:** `POST /api/ai/template-generator`

Template types: cold_outreach, follow_up, meeting_request, demo_booking, hr, recruitment, marketing, newsletter, promotion, events, invitation, reminder, thank_you, re_engagement

## AI Sequence Generator

**UI:** `/sequences/new`  
**API:** `POST /api/ai/sequence-generator`

Generates sequence name + steps (subject, body, delay days). User assigns templates before save.

## AI Segment Builder

**UI:** `/segments/new`  
**API:** `POST /api/ai/segment-builder`

Natural language → `SegmentFilters` (never auto-saved).

## AI Lead Scoring

**Fields:** `aiLeadScore` (0–100), `aiLeadGrade` (A–D), `aiScoreReason`, `aiScoredAt` on Lead, Company, Person

**API:** `POST /api/ai/lead-scoring` — `{ entityType, entityId }` or `{ entityType, entityIds[] }`

**UI:** Lead, Company, Person detail pages — **تقييم بالذكاء الاصطناعي**

## Next Best Action

**Service:** `ai-next-best-action.service.ts`  
**API:** `GET /api/ai/next-best-action?entityType=&entityId=`

Shown on Lead, Company, Person, Inbox thread CRM panel.

## Follow-Up Generator

**API:** `POST /api/ai/follow-up`  
**UI:** Inbox reply composer, Leads (via inbox link)

## AI Audit Log

**Model:** `AiActionLog` (`ai_action_logs`)

Tracks: email_generation, template_generation, sequence_generation, segment_builder, lead_scoring, next_best_action, reply_suggestion

Never stores API keys.

## Guard / validation

**API:** `GET /api/ai/guard`

- AI disabled → `الذكاء الاصطناعي غير مفعل`
- Missing provider key → `يرجى إعداد مزود الذكاء الاصطناعي أولاً`
- Returns `preferredLanguage` for UI defaults
- Falls back to rule-based output when OpenAI unavailable

## Services

| Service | Role |
|---------|------|
| `ai-guard.service.ts` | Availability, brand voice load, audit logging |
| `ai-generation.client.ts` | OpenAI JSON completion + brand voice |
| `ai-content.service.ts` | Email writer, template/sequence/segment/follow-up |
| `ai-lead-scoring.service.ts` | Single + bulk scoring |
| `ai-next-best-action.service.ts` | CRM recommendations |

## Related docs

- [08-ai-classification.md](./08-ai-classification.md) — inbox classification (Phase 1)
- [03-api-specification.md](./03-api-specification.md) — API index
