# AI Ad Review Integration Plan (Gemini Primary)

## Goal
Fully autonomous AI reviewer that **approves**, **rejects**, or **flags** seller ads
(`Product` records), using **Gemini as the primary AI**, grounded in the existing
**Post Ad Tips** ([`components/shop-create-tips.tsx`](components/shop-create-tips.tsx:70))
plus a stronger advanced rubric.

Guiding rules from the request:
- No good ad rejected, no bad ad approved (bias uncertainty toward FLAG, never toward a wrong decision).
- FLAG happens only when the AI is confused; the ad stays `PENDING` for a human.
- Reviews are **paced like a human**: a randomized **5-10 minute** delay before each ad is reviewed.
- The AI must **never** toggle Ad Boost (`promotedUntil` / `boosted`).

## Current State (verified)
- Ads = [`Product`](prisma/schema.prisma:356); statuses in [`Product_status`](prisma/schema.prisma:936).
- Create: [`app/api/products/route.ts`](app/api/products/route.ts:101) -> `status: 'PENDING'`.
- Seller resubmit/edit: [`app/api/products/[id]/route.ts`](app/api/products/[id]/route.ts:183) forces `PENDING`.
- Admin approve/reject + boost + notify/email: [`app/api/admin/products/route.ts`](app/api/admin/products/route.ts:88).
- Admin UI: [`app/admin-cp/components/marketplace-manager.tsx`](app/admin-cp/components/marketplace-manager.tsx:112).
- Gemini pattern: [`lib/chat-ai-moderation.ts`](lib/chat-ai-moderation.ts:130), cron AI: [`app/api/cron/refresh-quiz-banks/route.ts`](app/api/cron/refresh-quiz-banks/route.ts:8).
- Cron = external hits to `/api/cron/*` guarded by `CRON_SECRET`. No Redis/queue installed.
- Images on public R2 ([`app/api/upload/image/route.ts`](app/api/upload/image/route.ts:155)) -> Gemini can read them.

## Architecture
A DB-backed review queue (`AdAiReview`) polled by an external cron worker. This fits the
existing no-queue, cron-secret setup and gives durability, retries, audit, and human
resolution of FLAGs.

```mermaid
flowchart TD
    A[Seller submits ad] --> B[Product created as PENDING]
    B --> C[Enqueue AdAiReview with reviewAfter now plus 5 to 10 min]
    C --> D[Cron worker every 1 to 2 min]
    D --> E{Job due and unclaimed}
    E -->|No| D
    E -->|Yes| F[Claim job set IN_PROGRESS]
    F --> G[Fetch product text plus images]
    G --> H[Build rubric prompt from Post Ad Tips plus advanced rules]
    H --> I[Call Gemini primary]
    I --> J{Valid JSON result}
    J -->|No| K[Mark ERROR retry with backoff]
    K --> L{Attempts exhausted}
    L -->|Yes| M[FLAG for human review]
    L -->|No| D
    J -->|Yes| N[Apply deterministic threshold policy]
    N --> O{High confidence and all criteria pass}
    O -->|Yes| P[APPROVE]
    O -->|No| Q{High severity violation and confidence 95 plus}
    Q -->|Yes| R[REJECT with reason]
    Q -->|No| M[FLAG for human review]
    P --> S[Notify seller email plus in app]
    R --> S
    M --> T[Admin panel shows confusion notes]
    S --> U[Never modify Ad Boost]
```

## Data Model (Prisma)
Add `AdAiReview` and a relation on `Product`:

```prisma
model AdAiReview {
  id             String   @id @default(cuid())
  productId      String   @unique
  status         String   @default("QUEUED") // QUEUED | IN_PROGRESS | APPROVED | REJECTED | FLAGGED | ERROR
  attempt        Int      @default(0)
  reviewAfter    DateTime
  decidedAt      DateTime?
  confidence     Int?
  decision       String?  // APPROVE | REJECT | FLAG
  scores         Json?    // per-criterion rubric scores
  violations     Json?    // [{ code, severity, evidence }]
  confusionNotes String?  @db.Text
  provider       String?
  model          String?
  rawResponse    String?  @db.LongText
  createdAt      DateTime @default(now())
  updatedAt      DateTime @updatedAt
  product        Product  @relation(fields: [productId], references: [id], onDelete: Cascade)

  @@index([status, reviewAfter])
  @@index([productId])
}
```
`Product` gets `aiReview AdAiReview?`.

## Review Rubric (from Post Ad Tips + advanced)
Derived from the 10 tips + good/bad examples, expanded with safety checks:

1. Title clarity and specificity (exact product name, no vague words).
2. Real, relevant, high-quality images (no blurry, stock, watermarked, mismatched, NSFW).
3. Description completeness (what, who, size, color, condition, what buyer receives).
4. Category correctness and productType match (digital vs physical).
5. Honest, sane price (no bait/fake low price; statistical outlier vs category).
6. Delivery or access details present and plausible (location + deliveryDays, or working digital access).
7. Condition honesty (used/new matches text and images).
8. No approval problems (misleading, fake, confusing, missing key info).
9. Simple, buyer-friendly language (no jargon/gibberish/placeholder text).
10. Correct location and trust signals.
11. Prohibited items (weapons, drugs, counterfeit, adult, live animals, stolen, regulated).
12. Contact/payment leakage (phone, email, external links, WhatsApp, bank) — reuse
    [`containsPhoneNumber()`](lib/chat-validation.ts:1) plus link regex plus AI paraphrase detection.
13. Scam signals (too-good-to-be-true, urgency pressure).
14. Image-text consistency.
15. Duplicate/reposted listing detection (same seller, same title/images).
16. Seller context (banned, prior rejections) as read-only signal.

Gemini returns **strict JSON**:
```json
{
  "decision": "APPROVE | REJECT | FLAG",
  "confidence": 0,
  "summary": "short rationale",
  "criteria": [{ "id": "title_clarity", "score": 0, "passed": true, "note": "" }],
  "violations": [{ "code": "contact_leak", "severity": "LOW|MEDIUM|HIGH", "evidence": "" }],
  "confusion": ["why unsure"]
}
```

## Decision Policy (deterministic, code-side)
The model proposes; code decides via explicit thresholds so the model cannot overreach.

| Condition | Outcome |
|---|---|
| Any `HIGH` violation in hard-reject codes AND confidence >= 95 | REJECT (with reason) |
| All criteria passed AND no MEDIUM+ violation AND confidence >= 90 | APPROVE |
| Anything else (low confidence, confusion, mixed signals, provider failure) | FLAG (stays PENDING) |

Hard-reject codes: prohibited item, contact/payment leakage, clear scam, counterfeit.
Everything borderline -> FLAG. This enforces "never reject a good ad, never approve a bad ad".

## Key Files to Create / Change
- `prisma/schema.prisma` — add `AdAiReview` + relation.
- `lib/ad-ai-review.ts` (new) — rubric prompt builder, image fetch/base64, Gemini call,
  JSON parse/validate, decision policy engine, enqueue helper.
- `lib/product-approval.ts` (new) — shared `applyProductDecision()` for approve/reject side
  effects (in-app notification, seller badge, follower notify, email). Refactor
  [`app/api/admin/products/route.ts`](app/api/admin/products/route.ts:160) to call it so
  AI and admin paths behave identically.
- `app/api/products/route.ts` — enqueue `AdAiReview` after create with randomized `reviewAfter`.
- `app/api/products/[id]/route.ts` — re-enqueue on seller resubmission (status back to PENDING).
- `app/api/cron/ai-ad-review/route.ts` (new) — claim due jobs with atomic `updateMany`,
  enforce pacing between reviews, run review, apply decision, retries with backoff,
  fail-to-FLAG, never touch `promotedUntil`.
- `app/admin-cp/components/marketplace-manager.tsx` — add an **AI Review** tab listing
  FLAGGED ads with confusion notes, rubric scores, violations, and human Approve/Reject
  resolution; plus a read-only AI activity log.
- `app/account/components/my-shop.tsx` (or product page) — show "Under AI review" state.
- `scripts/backfill-ai-ad-reviews.ts` (new) — enqueue existing PENDING products.
- `scripts/test-ai-ad-review.ts` (new) — policy/threshold, enqueue timing, and Ad Boost guard tests.

## Safety and Guardrails
- **Ad Boost untouched**: the worker never writes `promotedUntil`/`boosted`; add an explicit
  regression test asserting the field is unchanged after a review.
- **Fail to FLAG, never to a wrong action**: provider/parse failures -> retry -> FLAG.
- **Idempotency/locking**: atomic claim (`updateMany` where status QUEUED) prevents double decisions.
- **No duplicate side effects**: only act on status transition (PENDING -> APPROVED/REJECTED).
- **Pacing**: randomized 5-10 min `reviewAfter`; worker processes a small batch per run with a
  short inter-ad delay to mimic human review.

## Config / Env
- `AI_AD_REVIEW_ENABLED` (kill switch)
- `AI_AD_REVIEW_DELAY_MIN` / `AI_AD_REVIEW_DELAY_MAX` (default 5 / 10 minutes)
- `AI_AD_REVIEW_APPROVE_CONFIDENCE` (default 90)
- `AI_AD_REVIEW_REJECT_CONFIDENCE` (default 95)
- `AI_AD_REVIEW_BATCH_SIZE` (default small, e.g. 3)
- `AI_AD_REVIEW_MODEL` (default `gemini-2.0-flash`)
- Reuse existing `GEMINI_API_KEY`; Groq/OpenRouter only as availability fallback.
- External cron entry hitting `/api/cron/ai-ad-review?secret=CRON_SECRET` every 1-2 minutes.

## Rollout
1. Schema + migration.
2. Shared services + enqueue hooks.
3. Cron worker behind `AI_AD_REVIEW_ENABLED` (start in FLAG-only mode to observe decisions).
4. Admin AI Review tab.
5. Backfill existing PENDING ads.
6. Enable autonomous APPROVE/REJECT once observed decisions look correct.
