# 2. Kien truc va luong du lieu (Data Flow)

## Architecture diagram

```mermaid
graph TD
    U[User Feedback] --> API[POST /autotrain/feedback]
    API --> FDB[feedbacks]
    FDB --> RUN[POST /autotrain/run-all]
    RUN --> AI[Mock AI]
    AI --> RULES[generated_rules]
    RULES --> REVIEW[Admin review]
    REVIEW --> APPROVE[approve / reject]
    APPROVE --> DEPLOY[POST /autotrain/rules/{rule_id}/deploy]
    DEPLOY --> DDB[deployments]
    DEPLOY --> FILE[backend/worker/fashion_rules.json]
```

---

## Flow chi tiet

### Step 1: Submit feedback

Request:

```json
POST /autotrain/feedback
{
  "query": "tim ao khoac cho troi 35 do",
  "ai_response": "Minh goi y ao khoac ni nay...",
  "feedback_text": "Troi nong qua, AI con tu van ao khoac",
  "feedback_type": "bug",
  "user_id": "CNF-98453"
}
```

He thong se:

1. Tao `feedback_id`
2. Luu vao bang `feedbacks`
3. Dat `status = pending`
4. Tra response co `feedback_id`, `status`, `created_at`

---

### Step 2: Process pending feedbacks

Route `POST /autotrain/run-all` lay tat ca feedback co `status = pending`, roi goi `generate_rule()` cho tung feedback.

Trang thai feedback:

`pending -> processing -> processed`

Neu validation fail:

`pending -> processing -> rejected`

---

### Step 3: Generate rule

`generate_rule()` thuc hien:

1. Lay feedback tu DB
2. Chuyen feedback sang `processing`
3. Goi `_ai_generate_rule()`
4. Validate rule
5. Insert vao `generated_rules`
6. Chuyen feedback sang `processed`

Ket qua insert vao `generated_rules` gom:

- `rule_id`
- `feedback_id`
- `module_name`
- `rule_type`
- `old_rule`
- `new_rule`
- `reasoning`
- `confidence`
- `status = pending`

---

### Step 4: Mock AI logic

Mock AI hien tai dung pattern matching, khong goi LLM.

Co 3 nhom pattern chinh:

1. Weather mismatch
2. Size / fit issue
3. Excessive emoji

Neu khong match pattern nao, he thong tao fallback rule voi `confidence = 0.5`.

---

### Step 5: Admin review

Route lien quan:

- `GET /autotrain/rules?status=pending`
- `GET /autotrain/rules/{rule_id}/validate`
- `POST /autotrain/rules/{rule_id}/approve`
- `POST /autotrain/rules/{rule_id}/reject`

Admin se review:

- `old_rule`
- `new_rule`
- `reasoning`
- `confidence`
- `module_name`

---

### Step 6: Deploy

Chi rule co `status = approved` moi deploy duoc.

Deploy hien tai la **deploy that**, khong con la mock-only:

1. Resolve target file tu `module_name`
2. Backup file hien tai
3. Mo `backend/worker/fashion_rules.json`
4. Append rule vao key `auto_train_rules`
5. Ghi file moi
6. Insert log vao bang `deployments`
7. Update `generated_rules.status = deployed`

Luu y quan trong:

- File `fashion_rules.json` trong repo nay la mot JSON config lon, khong phai mang `rules[]` don gian
- Vi vay Auto-Train append vao `auto_train_rules[]` de tranh pha schema cua worker hien co

---

### Step 7: Production use

Sau khi deploy, rule moi nam trong `fashion_rules.json`.

Tai lieu nay **khong gia dinh** chatbot da hot-reload ngay lap tuc. Trang thai hien tai:

- File duoc cap nhat thanh cong
- Phan co che reload config cua chatbot van la viec rieng, chua duoc Auto-Train quan ly

---

## Component interaction

```mermaid
graph LR
    F[feedbacks] -->|select pending| W[run-all]
    W -->|generate| AI[_ai_generate_rule]
    AI -->|validated insert| R[generated_rules]
    R -->|approve/reject| A[Admin]
    A -->|approved| D[deploy_rule]
    D -->|write| P[fashion_rules.json]
    D -->|insert log| L[deployments]
```

---

## Data flow summary

| Step | Input | Output | Storage |
|---|---|---|---|
| Submit | Feedback JSON | `feedback_id` | `feedbacks` |
| Generate | `feedbacks` row | `rule_id`, `new_rule` | `generated_rules` |
| Review | `generated_rules` row | `approved` / `rejected` | `generated_rules` |
| Deploy | Approved rule | Backup + file update + deployment log | `deployments` + `fashion_rules.json` |

---

## Error handling hien tai

- `404`: feedback hoac rule khong ton tai
- `400`: deploy khi rule chua approved
- `422`: rule fail validation
- `500`: target file hoac JSON structure khong hop le

---

## Gioi han hien tai

- SQLite phu hop cho mock/dev, khong hop production scale lon
- `run-all` van chay sync
- Chua co queue/background worker dung nghia
- Chua co rollback endpoint
- Chua co conflict detection giua cac rule da deploy
