# WP AI Chat Assistance - Plugin Knowledge Base

Purpose: this file is a permanent context index for AI assistants and developers so they do not need to re-study the plugin on every new prompt.

## 1. What This Plugin Does

WP AI Chat Assistance adds a storefront chat widget for WooCommerce. It:
- Renders a floating chat bubble and chat window on the frontend.
- Accepts user questions through a REST API endpoint.
- Finds relevant WooCommerce products and includes them in AI responses.
- Calls OpenRouter chat-completions API for the final assistant message.
- Provides an admin settings screen (React app) to configure behavior, model, limits, and appearance.

## 2. Source Of Truth Files

Core runtime:
- `aco-smart-ai-assistant.php` - plugin bootstrap, frontend enqueue, widget HTML, chat REST route registration.
- `includes/class-chat-handler.php` - chat endpoint logic, rate limiting, product search, OpenRouter request, usage tracking.
- `includes/class-admin-settings.php` - admin menu, option registration/sanitization, admin REST settings endpoint.

Admin frontend source:
- `app/src/admin/Backend.jsx`
- `app/src/admin/api/settingsApi.js`
- `app/src/admin/components/AdminTabs.jsx`
- `app/src/admin/components/SettingField.jsx`

Frontend source (not currently built to live frontend bundle):
- `app/src/Frontend.jsx`

Built/runtime assets:
- `assets/js/chat-frontend.js` - active storefront chat JS (vanilla JS).
- `assets/css/chat-style.css` - storefront styles.
- `assets/js/admin.js` - built admin React bundle.
- `assets/css/admin-style.css` - built admin CSS.

Build config:
- `app/package.json`
- `app/webpack.config.js`

## 3. Bootstrap And Lifecycle

Main class: `WP_AI_Chat_Assistance` in `aco-smart-ai-assistant.php`.

Initialization flow:
1. Plugin loads constants: `WP_AI_CHAT_VERSION`, `WP_AI_CHAT_URL`, `WP_AI_CHAT_PATH`.
2. Includes admin settings class and chat handler class.
3. Creates `Chat_Handler` instance.
4. On WordPress `init`, checks `wp_ai_chat_enabled` (default `yes`).
5. If enabled, registers:
   - `wp_enqueue_scripts` -> `enqueue_frontend()`
   - `wp_footer` -> `render_chat_widget()`
   - `rest_api_init` -> `register_rest()`

No activation/deactivation hook is defined.

## 4. Frontend Runtime (Storefront)

### 4.1 Enqueued Data

`enqueue_frontend()` localizes `window.wpAIChat` with:
- `assistant_name`
- `welcome_message`
- `api_url` (`/wp-ai-chat/v1/chat`)
- `nonce` (`wp_create_nonce('wp_ai_chat_nonce')`)
- `position`
- `primary_color`
- `bubble_icon`
- `default_theme`
- `is_logged_in`
- `currency_symbol`
- `api_configured` (derived from `wp_ai_chat_openrouter_key`)

### 4.2 Widget Markup

`render_chat_widget()` outputs:
- Bubble button
- Header (assistant name + theme/clear/close actions)
- Message area
- Quick reply buttons
- Input and send button

Quick replies are generated dynamically based on store average product price.

### 4.3 Active Frontend Script

Live storefront behavior is implemented by `assets/js/chat-frontend.js` (vanilla JS), not by a webpack-built React frontend bundle.

Key behavior:
- Opens/closes chat window.
- Persists chat history in localStorage.
  - Logged-in: `wpAIChatHistoryUser`
  - Guest: `wpAIChatHistorySession`
- Sends POST request to chat REST endpoint.
- Renders assistant messages and product cards.
- Supports WooCommerce add-to-cart via AJAX with URL fallback.
- Theme toggle between light/dark.

Nonce header used by frontend request: `X-WP-AI-Nonce`.

## 5. REST APIs

### 5.1 Public Chat API

Route:
- `POST /wp-json/wp-ai-chat/v1/chat`

Registered in `WP_AI_Chat_Assistance::register_rest()`.

Callback:
- `Chat_Handler::handle()`

Permission callback:
- `Chat_Handler::permission_check()` returns `true` (public endpoint).

Practical protections in handler:
- Message sanitization.
- Rate limiting by IP transient.
- Daily/monthly usage limit checks.
- Fallback response on API errors.

### 5.2 Admin Settings API

Route:
- `GET /wp-json/wp-ai-chat/v1/admin/settings`
- `POST /wp-json/wp-ai-chat/v1/admin/settings`

Registered in `WP_AI_Chat_Admin_Settings::register_rest_routes()`.

Permission:
- `current_user_can('manage_options')`.

Used by admin React app (`app/src/admin/api/settingsApi.js`) with header:
- `X-WP-Nonce` (`wp_rest` nonce)

## 6. Chat Request Processing Pipeline

In `Chat_Handler::handle()`:
1. Validate WooCommerce class exists.
2. Rate limit check (`allow_request_rate()`, 20 req/IP/minute).
3. Read and sanitize incoming `message`.
4. If OpenRouter key exists, run AI query planner (`generate_product_query_plan()`) to produce structured JSON:
  - intent
  - search term
  - max price
  - in-stock flag
  - compare items
  - sort mode
5. Find relevant products via `find_relevant_products($message, $query_plan)`.
6. Increment `wp_ai_chat_total_chats`.
7. If no OpenRouter key -> return fallback message + product cards.
8. Enforce token usage caps (`usage_limit_available()`).
9. Build prompt with store name, settings knowledge, and top products.
10. Call OpenRouter with fallback model strategy (`request_ai()`).
11. On success: return assistant message + product cards + usage tokens.
12. On failure: increment `wp_ai_chat_failed_queries`, return fallback.

## 7. Product Matching Logic

`find_relevant_products()`:
- Converts message to lowercase.
- Uses AI query plan first when available, then falls back to local keyword extraction.
- Uses up to 3 keywords and max 3 products.
- Optional max budget extraction (supports patterns like under $50, INR/rupees/rs).
- Optional stock filter if user asks for "in stock" / "available".
- Handles compare intent by extracting two product phrases and fetching one best match for each.
- Supports sort intent (`price_asc`, `price_desc`, `rating_desc`) from planner output.

Product card payload includes:
- id, name, description, price, sale_price, sku
- stock_status
- categories, tags, attributes
- image, url
- add_to_cart_url (only for simple + purchasable + in stock)

## 8. AI Provider And Model Strategy

Current active provider:
- OpenRouter only.

Key settings used in request:
- `wp_ai_chat_model`
- `wp_ai_chat_temperature`
- `wp_ai_chat_max_tokens`
- `wp_ai_chat_timeout`

Model fallback behavior:
- Preferred model first.
- Then cached free models from OpenRouter `/models` endpoint.
- Then hardcoded free model list.
- Retries on retryable failures (5xx, 429, no endpoints, temporary unavailable).

Headers sent to OpenRouter:
- Authorization: Bearer key
- Content-Type: application/json
- HTTP-Referer: site home URL
- X-Title: site name

## 9. Usage Tracking And Limits

Usage options:
- Daily limit: `wp_ai_chat_daily_limit`
- Monthly limit: `wp_ai_chat_monthly_limit`

Counters/metrics:
- `wp_ai_chat_usage_daily_YYYYMMDD`
- `wp_ai_chat_usage_monthly_YYYYMM`
- `wp_ai_chat_total_chats`
- `wp_ai_chat_failed_queries`

If usage limit reached, chat returns HTTP 429 with message.

## 10. Settings Keys (Canonical List)

General:
- `wp_ai_chat_enabled` (`yes`/`no`)
- `wp_ai_chat_assistant_name`
- `wp_ai_chat_welcome_message`

Appearance:
- `wp_ai_chat_chat_position` (`bottom-right`, `bottom-left`)
- `wp_ai_chat_chat_color`
- `wp_ai_chat_bubble_icon` (`chat`, `spark`, `bolt`)
- `wp_ai_chat_default_theme` (`light`, `dark`)

API/model:
- `wp_ai_chat_openrouter_key`
- `wp_ai_chat_ai_tool` (sanitizer currently only allows `openrouter`)
- `wp_ai_chat_model`
- `wp_ai_chat_temperature` (0..2)
- `wp_ai_chat_max_tokens`
- `wp_ai_chat_timeout`
- `wp_ai_chat_daily_limit`
- `wp_ai_chat_monthly_limit`

Behavior:
- `wp_ai_chat_restrict_product_only` (`yes`/`no`)
- `wp_ai_chat_fallback_response`
- `wp_ai_chat_knowledge_text`

## 11. Security And Sanitization Notes

- Public chat endpoint intentionally allows guests.
- Input message sanitized with `sanitize_text_field()`.
- AI message returned through `wp_kses_post()`.
- Product text in cards is stripped/sanitized.
- Settings are sanitized per-field by callbacks in admin settings class.
- API keys are stored in WordPress options and not exposed directly to frontend.

Important nuance:
- The frontend sends header `X-WP-AI-Nonce`, while WordPress standard checks expect `X-WP-Nonce`. Current chat endpoint does not enforce nonce verification in handler, so requests still work.

## 12. Build Pipeline Reality

Webpack (`app/webpack.config.js`) currently builds only:
- entry `./src/admin/main.jsx` -> `assets/js/admin.js`
- CSS -> `assets/css/admin-style.css`

This means:
- Admin UI is React and built from `app/src/admin/*`.
- Frontend chat currently runs from static `assets/js/chat-frontend.js`.
- `app/src/Frontend.jsx` appears to be source for an alternative React frontend implementation, but is not wired into webpack output in current config.

Build command:
- Run in `app/`: `npm run build`

## 13. Known Gaps / Risks

- Debug logging (`error_log`) is active in chat handler and can produce noisy logs in production.
- Chat endpoint is public and nonce is not validated server-side (rate limits mitigate abuse but do not fully secure endpoint).
- `wp_ai_chat_ai_tool` UI shows future providers, but backend sanitizer only accepts `openrouter`.
- There are two frontend implementations (vanilla runtime + React source), which can cause maintenance confusion.

## 14. Quick Dev Checklist

If chat does not answer:
1. Verify WooCommerce is active.
2. Verify `wp_ai_chat_enabled=yes`.
3. Confirm OpenRouter key exists in `wp_ai_chat_openrouter_key`.
4. Check token usage limits are not exceeded.
5. Inspect PHP logs for `WP AI Chat` entries.
6. Inspect network call to `/wp-json/wp-ai-chat/v1/chat`.

If settings page fails:
1. Confirm user has `manage_options`.
2. Verify `assets/js/admin.js` and `assets/css/admin-style.css` exist.
3. Check `wpAIChatAdmin.api_url` and `wpAIChatAdmin.nonce` are localized.
4. Inspect REST response from `/wp-json/wp-ai-chat/v1/admin/settings`.

## 15. Reusable AI Prompt Context

Use this text in future AI requests:

"Read `PLUGIN_KNOWLEDGE_BASE.md` first and use it as the primary plugin context. Avoid re-scanning the whole codebase unless requested or if the file is outdated. When proposing changes, reference the documented architecture and option keys from that file."

## 16. Update Rule

Whenever plugin architecture, settings keys, or request flow changes:
- Update this file in the same PR/commit.
- Keep section 10 (settings keys) and section 12 (build pipeline) accurate.
