# Content AI Manager Backend Task

## Goal

Build a simple operator-controlled backend layer for the public content AI manager inside `hub.bent.ge`.

This is not a new standalone system.
This is an extension of the existing content module and existing public translation/content services.

The operator must be able to:

- run content audit manually
- see what the AI wants to do before it changes anything
- execute every step manually
- rerun one failed step without rerunning the whole flow
- give custom AI tasks in free text
- generate missing locales
- refresh stale text
- create article drafts
- generate image briefs and images
- attach images to content
- publish/export only when explicitly approved

## Hard Rules

- Do not build a second CMS.
- Do not build a separate microservice.
- Do not move business rules into prompts.
- Do not auto-publish by default.
- Do not auto-run cron generation by default in the first release.
- Do not store critical prompt logic only in AI Studio.
- AI Studio is for prompt/schema testing only.
- Production source of truth stays in Laravel + MySQL + `content_items`.
- Reuse existing services first:
  - `backend/app/Support/PublicSite/PublicContentAiTranslationService.php`
  - `backend/app/Support/PublicSite/PublicContentTranslationAnalyzer.php`
  - `backend/app/Support/PublicSite/PublicTranslationAgentService.php`
  - `backend/app/Support/PublicSite/ContentAiManagerService.php`
  - `backend/app/Http/Controllers/Api/ContentController.php`

## Current Base Already Exists

The following already exists and must be extended, not replaced:

- Gemini/OpenAI provider switch for content translation
- content AI audit service
- content AI audit endpoint
- content AI actions:
  - fill missing locale
  - create article draft
- current content screen already contains AI audit card

This task is about turning that base into a controllable operator workflow.

## Required Operator Flows

### 1. Manual Audit Run

Operator opens content AI manager and runs audit manually.

Audit must show:

- missing locales
- stale translations
- article cadence gap
- recommended next actions
- provider/model currently active

### 2. Guided Locale Fill Run

Operator chooses:

- one content group
- one or many missing locales

System creates a run with visible steps:

1. fetch source item
2. verify locale is missing
3. generate translation
4. save draft translation
5. optional publish
6. optional export

### 3. Guided Article Draft Run

Operator chooses:

- locale
- category
- optional brief
- optional target count

System creates a run with visible steps:

1. inspect recent article cadence
2. inspect recent article topics
3. inspect FAQ/support topics for safe source material
4. generate draft article
5. save draft
6. optional generate image brief
7. optional generate image
8. optional attach image
9. optional publish
10. optional export

### 4. Custom Task Run

Operator enters free text such as:

- `generate 3 new airport pickup drafts in en and ru`
- `refresh german locale for all offers`
- `rewrite faq tone for french`
- `generate image for this article`

Backend must not execute that blindly.
It must first convert it into a structured run plan with steps and targets, then expose it to the operator for manual execution step by step.

## Minimal Persistence

Do not overbuild.
Use only two new tables.

### `content_ai_runs`

Purpose:

- one operator-visible run

Recommended fields:

- `id`
- `type`
  - `audit`
  - `fill_missing_locales`
  - `refresh_stale_content`
  - `create_article_draft`
  - `generate_images`
  - `custom`
- `status`
  - `draft`
  - `planned`
  - `running`
  - `paused`
  - `completed`
  - `failed`
  - `cancelled`
- `provider`
- `model`
- `requested_by_user_id`
- `scope_json`
- `input_json`
- `plan_json`
- `result_summary_json`
- `last_error`
- `started_at`
- `finished_at`
- `created_at`
- `updated_at`

### `content_ai_run_steps`

Purpose:

- each executable step inside one run

Recommended fields:

- `id`
- `content_ai_run_id`
- `step_key`
- `step_type`
- `position`
- `status`
  - `pending`
  - `running`
  - `proposed`
  - `approved`
  - `applied`
  - `failed`
  - `skipped`
- `target_type`
- `target_content_item_id`
- `target_locale`
- `input_json`
- `output_json`
- `last_error`
- `started_at`
- `finished_at`
- `created_at`
- `updated_at`

No third orchestration table is needed in v1.

## Required Backend Services

### `ContentAiManagerService`

Must become the main orchestration entry point.

Responsibilities:

- create run plans
- expose available actions
- execute a single step
- resume a run
- rerun a single failed step
- summarize results

### `ContentAiRunPlannerService`

New small service.

Responsibilities:

- turn preset actions or free-text custom task into a backend plan
- choose the correct step sequence
- validate scope
- resolve target content groups

### `ContentAiRunExecutorService`

New small service.

Responsibilities:

- execute one step only
- call existing content translation/article/image services
- write step result/output/error
- never bypass validation

### `ContentAiPromptService`

New small service.

Responsibilities:

- hold prompt builders in code
- separate prompt construction from controller/service logic
- keep AI Studio prompt experiments out of runtime logic

## Required API

All of this must live under the current content API area.

### Overview / control

- `GET /api/content/ai-manager/overview`
  - returns active provider/model
  - latest audit summary
  - latest runs
  - quick counters

### Run creation

- `POST /api/content/ai-manager/runs`
  - create a run from preset or custom task

Input examples:

```json
{
  "type": "fill_missing_locales",
  "scope": {
    "content_type": "offer",
    "content_key": "range_rover_sport_special",
    "locales": ["fr", "de"]
  }
}
```

```json
{
  "type": "custom",
  "instruction": "generate 2 new article drafts about airport pickup in english and russian"
}
```

### Run read

- `GET /api/content/ai-manager/runs`
- `GET /api/content/ai-manager/runs/{run}`

### Step control

- `POST /api/content/ai-manager/runs/{run}/steps/{step}/execute`
- `POST /api/content/ai-manager/runs/{run}/steps/{step}/approve`
- `POST /api/content/ai-manager/runs/{run}/steps/{step}/reject`
- `POST /api/content/ai-manager/runs/{run}/steps/{step}/rerun`

### Run control

- `POST /api/content/ai-manager/runs/{run}/resume`
- `POST /api/content/ai-manager/runs/{run}/cancel`

### Existing direct helpers

Current direct helpers may stay:

- `GET /api/content/ai-audit`
- `POST /api/content/ai-actions/fill-missing-locale`
- `POST /api/content/ai-actions/create-article-draft`

But the new manager should become the operator-facing control layer above them.

## Required Artisan Commands

Need manual CLI control for debugging and ops.

### `content:ai-audit`

Already exists.
Keep it.

### `content:ai-run`

Create a run manually from CLI.

Examples:

```bash
php artisan content:ai-run --type=audit
php artisan content:ai-run --type=fill_missing_locales --content-type=offer --content-key=range_rover_special --locales=fr,de
php artisan content:ai-run --type=create_article_draft --locale=en --brief="airport pickup article"
php artisan content:ai-run --type=custom --instruction="refresh stale german offer locales"
```

### `content:ai-step`

Execute or rerun one step.

Examples:

```bash
php artisan content:ai-step 15 3 --execute
php artisan content:ai-step 15 3 --rerun
```

### `content:ai-runner`

Optional helper for future cron/manual batch use.
Not enabled in scheduler by default in v1.

## Step Types

Use a compact fixed catalog.

- `scan_scope`
- `resolve_targets`
- `generate_locale`
- `refresh_locale`
- `generate_article_draft`
- `generate_image_brief`
- `generate_image`
- `attach_media`
- `save_draft`
- `publish_content`
- `run_public_export`

Do not create phrase-specific dynamic step types.

## Custom Task Behavior

Custom task does not mean direct execution.

Flow must be:

1. operator enters instruction
2. backend sends instruction + scope context to Gemini
3. Gemini returns structured run plan only
4. backend validates the plan
5. backend stores run + steps
6. operator executes steps manually

This is critical.
The model is a planner, not an auto-executor.

## Gemini / AI Studio Rules

### Provider

Use current provider config:

- `CONTENT_AI_PROVIDER=gemini`
- `GEMINI_API_KEY=...`
- `GEMINI_CONTENT_TRANSLATION_MODEL=gemini-3.1-pro-preview`
- `GEMINI_CONTENT_MANAGER_MODEL=gemini-3.1-pro-preview`

### Free tier

Support free tier first.
That means:

- manual runs first
- no background spam
- no uncontrolled multi-step loops
- clear error handling for quota/429

### AI Studio

Use AI Studio only for:

- prompt testing
- schema testing
- sample run experiments

Do not depend on AI Studio state for runtime behavior.
All production prompts and schemas must live in code.

## Image Generation

Do not bolt image generation directly into article publish.

For v1:

1. generate image brief
2. operator can edit the brief
3. generate image
4. operator chooses whether to attach it

If image generation provider is not ready, still ship the step flow and store brief output.
Do not hide the missing provider behind fake success.

## Publish Rules

- Draft creation is allowed automatically.
- Publish is never automatic in v1.
- Export is never automatic in v1 unless operator explicitly triggers it.
- If a generated locale/article still looks identical to the source, block publish.
- If article/image generation fails, run status must stay recoverable.

## UI Contract For Frontend

Backend must support a single operator panel inside current content module.

Frontend needs:

- overview payload
- run list
- run detail
- step detail
- execute step
- approve/reject step
- rerun step

Do not require frontend to reconstruct business state from raw logs.

## Acceptance

This task is done only when:

1. operator can run audit manually from UI and CLI
2. operator can create a run manually from preset action
3. operator can create a run manually from custom instruction
4. backend returns a visible step plan before execution
5. each step can be executed separately
6. one failed step can be rerun without recreating the run
7. article draft generation works into `Draft / Private`
8. missing locale generation works into draft/current translation flow
9. publish and export are explicit manual actions
10. Gemini free-tier quota errors are surfaced cleanly
11. no second CMS or second admin area was introduced

## Do Not Do

- do not build autonomous cron publishing
- do not build a separate content-ai frontend app
- do not create a huge workflow engine
- do not move content truth into AI Studio
- do not let prompts decide publish rules
- do not create fake article/image success states
