# Deployment (BE) — QuitSure AI Support

Same model as **Discovery**: Apache reverse-proxy in front of `uvicorn app:app`, the proxy
**strips the `/support-ai` prefix** so the app mounts at `/`. Pull-and-go, no build step.

## Public URL (test)
```
https://tweb.quitsure.app/support-ai/
```
Routes (proxy strips the prefix, so uvicorn sees them at root):
`/support-ai/chat` · `/support-ai/health` · `/support-ai/feedback` · `/support-ai/stats`
· `/support-ai/` (internal test UI) · `/support-ai/analytics` (dashboard)

Serve `/support-ai/` **with a trailing slash**, like `/discovery/`.

## Run
- Python 3.9+, `pip install -r requirements.txt`
- Put `.env` in the project root (see `.env.example`)
- `uvicorn app:app --host 0.0.0.0 --port <PORT>`  (we use 8082 locally)
- Apache reverse-proxies `/support-ai/` to this uvicorn, **stripping** `/support-ai` (same as
  `/discovery`). The app mounts at `/` by default.
- If the proxy instead **forwards** the prefix through, set `MOUNT_PREFIX=/support-ai` in `.env`
  (the app supports both, verified).

## .env
```
GEMINI_API_KEY=...            # required
GEMINI_MODEL=gemini-2.5-flash
GEMINI_EMBED_MODEL=gemini-embedding-001
RETRIEVAL_FLOOR=0.55
# test DB: same host/creds as the discovery / chatbot-onboarding services
DB_HOST=...
DB_PORT=3306
DB_DATABASE=quitsure
DB_USERNAME=...
DB_PASSWORD=...
# MOUNT_PREFIX=            # leave empty for strip-proxy; set /support-ai if the proxy forwards it
```

## Knowledge
`data/kb.json` and `data/index.npz` are **committed** (pull-and-go, no build needed to run).
To refresh after the knowledge Excel changes:
`python3 scripts/build_kb.py && python3 scripts/build_index.py` (build_index needs `GEMINI_API_KEY`
+ internet), then commit and redeploy.

## DB
Tables already created in the test DB: `tbl_SupportChatLog`, `tbl_SupportChatFeedback`
(`docs/DB_SCHEMA.sql`). The app user needs **INSERT + SELECT** on both. Logging is best-effort:
if the DB is unreachable it no-ops and never breaks a reply.

## Health check
`GET /support-ai/health` → `{"status":"ok","kb_entries":483,"model":"gemini-2.5-flash",...}`

## Auth (shared secret key)
Set `API_KEY` in `.env` to a strong random value. Then `/chat`, `/feedback`, and `/stats` require
callers to send that value as the `X-API-Key` header, anything else gets `401`. `/health` stays open
(for proxy health checks).
- **Mobile app:** send `X-API-Key: <the key>` on every `/chat` call.
- **Test UI / dashboard:** open with the key in the URL, e.g. `…/support-ai/?key=<the key>` and
  `…/support-ai/analytics?key=<the key>`.
- Leave `API_KEY` empty in local dev to keep it open (no key needed).
