# ACA — AI Commerce Aggregator

## 1. Project Overview

**ACA** is a standalone Django-based conversational commerce platform that acts as an intelligent shopping layer on top of any number of independent eCommerce stores. It does not sell products itself — it aggregates, recommends, compares, and redirects users to the originating store for checkout.

### Core Principles

- **Store-agnostic**: Not hardcoded to any fixed number of stores. New stores are registered dynamically through the Django admin panel.
- **API-only data**: The AI never scrapes, fabricates, or caches stale product data as truth. All product information is fetched live (or from a controlled sync) from registered store APIs.
- **Conversational UX**: Users interact through a chat interface. The AI collects preferences through natural dialogue, builds structured queries, fetches matching products, and presents intelligent recommendations.
- **Zero checkout responsibility**: ACA never processes payments, stores credit cards, or manages orders. It redirects the user to the store's product page.

---

## 2. Architecture

```
User (Browser)
    │
    ▼
┌─────────────────────────┐
│   Django Web App (ACA)  │
│  ┌───────────────────┐  │
│  │   Chat Frontend   │  │  ← HTMX / React chat UI
│  └────────┬──────────┘  │
│           ▼             │
│  ┌───────────────────┐  │
│  │   AI Engine        │  │  ← Conversation manager, intent detection, slot filling
│  │   (LLM + Logic)   │  │
│  └────────┬──────────┘  │
│           ▼             │
│  ┌───────────────────┐  │
│  │ Product Gateway    │  │  ← Fans out API calls to N registered stores
│  │ (Aggregator)       │  │
│  └────────┬──────────┘  │
│           ▼             │
│  ┌───────────────────┐  │
│  │  Store Registry    │  │  ← Admin-managed list of stores + credentials
│  └───────────────────┘  │
└─────────────┬───────────┘
              │  HTTP/REST calls
              ▼
    ┌─────────────────┐
    │  Store A API     │
    │  Store B API     │
    │  Store C API     │   ← Any number of independent stores
    │  Store ...  API  │
    └────────┬────────┘
             │
             ▼
    User redirected to store checkout
```

---

## 3. Key Components

### 3.1 Store Registry (Pluggable Store System)

Stores are **not hardcoded**. Each store is a database record managed via Django admin:

| Field              | Description                                      |
|--------------------|--------------------------------------------------|
| `name`             | Human-readable store name                        |
| `slug`             | URL-safe identifier                              |
| `base_api_url`     | Root URL of the store's API                      |
| `api_key`          | Authentication credential                        |
| `auth_method`      | How to authenticate (API key header, Bearer, etc)|
| `is_active`        | Toggle store on/off without deleting             |
| `logo`             | Store branding for display in chat               |
| `priority`         | Ordering weight for result ranking               |
| `search_endpoint`  | Path appended to base URL for product search     |
| `detail_endpoint`  | Path pattern for single product detail           |
| `response_mapping` | JSON field mapping config for normalization       |
| `added_at`         | Timestamp                                        |

An admin can add a new store in under a minute. No code changes required.

### 3.2 AI Engine

The intelligence layer that turns conversation into commerce.

**Conversation Manager**
- Maintains per-session context and memory
- Detects user intent (browsing, searching, comparing, deep-diving)
- Performs slot filling: extracts structured attributes (category, size, color, budget, brand, gender, purpose) from natural language
- Generates follow-up questions when information is insufficient

**Product Query Builder**
- Converts the filled slots into a normalized query dict:
```json
{
  "category": "shoes",
  "gender": "male",
  "purpose": "running",
  "budget_min": 50,
  "budget_max": 150,
  "size": "42",
  "color": "black",
  "brand": "adidas"
}
```

**LLM Layer**
- Powers natural language understanding and generation
- Enhances product descriptions for the user
- Generates pros/cons, comparisons, and buying advice
- Provider-agnostic: supports OpenAI, Anthropic Claude, or local models via a unified interface
- Includes prompt injection filtering and hallucination guardrails

### 3.3 Product Gateway (Aggregator)

The service that fans out queries to all active stores:

1. Read active stores from `StoreRegistry`
2. For each store, build the appropriate API request using that store's endpoint config
3. Execute requests concurrently (async with `httpx`)
4. Normalize each store's response using the store's `response_mapping`
5. Merge, deduplicate, and rank results
6. Return a unified product list to the AI engine

Handles: timeouts, retries, partial failures (if Store C is down, results from A and B still appear).

### 3.4 Ranking & Personalization

After aggregation, products are scored:

| Signal                 | Weight | Description                                |
|------------------------|--------|--------------------------------------------|
| Query match            | High   | How closely attributes match the query     |
| Budget proximity       | High   | Distance from user's stated budget         |
| Brand preference       | Medium | User's historical or stated brand affinity |
| Store priority         | Low    | Admin-configured store weight              |
| Personalization score  | Medium | Based on user profile history if available |

### 3.5 Chat Frontend

- Chat-style interface embedded in the Django app
- Product cards rendered inline within conversation
- Conversation history persisted per session/user
- "Buy from [Store Name]" buttons redirect to the store's product URL
- Stack: Django templates + HTMX for real-time updates (upgradeable to React or Django Channels/WebSocket)

---

## 4. Conversation Modes

| Mode            | Trigger                                         | Behavior                                                    |
|-----------------|--------------------------------------------------|-------------------------------------------------------------|
| **Discovery**   | Vague input ("I need something nice")            | AI asks guided questions to narrow down preferences         |
| **Direct**      | Specific input ("Adidas black running shoes 42") | AI extracts structured data immediately, queries stores     |
| **Deep Dive**   | User selects a specific product                  | AI provides pros, cons, alternatives, comparisons           |
| **Comparison**  | User asks to compare two or more products        | Side-by-side analysis with AI commentary                    |

---

## 5. Data Models

### Conversation & Messaging
- **Conversation**: ties to a user/session, tracks timestamps
- **Message**: belongs to a conversation, stores role (user/assistant/system), content, and optional product references

### User Preferences
- **UserPreferenceProfile**: preferred brands, budget range, sizes, gender, category interests — built over time from conversations

### Store Management
- **StoreRegistry**: the pluggable store record described in §3.1
- **StoreHealthLog**: tracks API response times, failures, uptime per store

### Product Cache (Optional)
- **CachedProduct**: short-lived local cache of product data to reduce redundant API calls (TTL: 5–15 minutes via Redis)

---

## 6. Store API Contract

Each registered store must expose at minimum:

**Product Search** — `GET {base_api_url}/{search_endpoint}/`

Query parameters (all optional):
```
?category=shoes&gender=male&min_price=50&max_price=150&size=42&color=black&brand=adidas&q=running
```

Response (JSON array):
```json
[
  {
    "id": 123,
    "name": "Nike Air Zoom Pegasus",
    "price": 120.00,
    "currency": "USD",
    "image_url": "https://store.example.com/media/shoe.jpg",
    "description": "Lightweight running shoe...",
    "brand": "Nike",
    "category": "shoes",
    "product_url": "https://store.example.com/product/123/",
    "in_stock": true
  }
]
```

**Product Detail** — `GET {base_api_url}/{detail_endpoint}/{id}/`

Returns a single product with extended fields (specifications, reviews summary, related products).

> The `response_mapping` field on StoreRegistry allows ACA to normalize varying field names across stores (e.g., one store calls it `img`, another `image_url`).

---

## 7. Order Flow

```
User sees product card in chat
    → Clicks "Buy from StoreName"
    → Browser redirects to store's product_url
    → User adds to cart on store site
    → User checks out on store site
    → ACA is not involved in payment
```

Future extensions: cart API integration, affiliate link tracking, cross-store unified cart.

---

## 8. Caching Strategy

| What                  | Backend | TTL         |
|-----------------------|---------|-------------|
| Frequent searches     | Redis   | 5–10 min    |
| Popular products      | Redis   | 10–15 min   |
| Store metadata        | Redis   | 1 hour      |
| Conversation context  | Redis   | Session TTL |

---

## 9. Security

- Store API keys encrypted at rest, never exposed to the frontend
- JWT or API-key authentication between ACA and stores
- Rate limiting on chat endpoints
- Input sanitization on all user messages
- LLM prompt injection filtering (system prompt hardening, input validation layer)
- ACA never stores payment or sensitive PII from stores

---

## 10. Design Rules (Non-Negotiable)

1. ACA must **never invent products** — every product shown must come from a store API response.
2. ACA must **never modify pricing** — prices are displayed exactly as returned.
3. ACA must **never process payments** — always redirect to the store.
4. ACA must **never store sensitive checkout data**.
5. Stores are **pluggable** — adding or removing a store is an admin action, not a code change.

---

## 11. Development Phases

### Phase 1 — MVP
- Django project scaffold with core models
- Store registry with admin management
- Basic chat UI (HTMX)
- Conversation manager with slot filling
- Product gateway (synchronous, single-store)
- LLM integration (OpenAI)
- Product cards in chat with redirect links

### Phase 2 — Multi-Store & Intelligence
- Multiple stores with concurrent async fetching
- Response normalization via mapping configs
- Personalization engine
- Redis caching layer
- Deep dive and comparison modes
- Conversation history persistence

### Phase 3 — Scale & Optimize
- Celery for background product index refresh
- Internal search index (Elasticsearch/Meilisearch) for hybrid live+indexed queries
- Store analytics dashboard
- Advanced ranking algorithms
- WebSocket real-time chat (Django Channels)

### Phase 4 — Expansion
- Mobile app / PWA
- WhatsApp / Telegram bot integration
- Voice AI shopping
- Dynamic price alerts
- AI wardrobe memory / style profiles
- Cross-store cart system

---

## 12. Tech Stack

| Layer             | Technology                              |
|-------------------|-----------------------------------------|
| Backend           | Django 5.x, Django REST Framework       |
| Database          | PostgreSQL                              |
| Cache             | Redis                                   |
| Task Queue        | Celery + Redis broker                   |
| LLM               | OpenAI API (swappable)                  |
| HTTP Client       | httpx (async support)                   |
| Frontend          | Django Templates + HTMX (Phase 1)      |
| Real-time         | Django Channels (Phase 3)               |
| Search (future)   | Meilisearch or Elasticsearch            |

---

## 13. Monetization Paths

- Commission per redirected sale (affiliate model)
- Featured/sponsored product placement
- Store subscription fee for listing
- Analytics dashboard access for store owners
- Premium AI shopping assistant for consumers
