# 1. Tong quan (Overview)

## Auto-Train la gi?

**Auto-Train** la pipeline nhan user feedback ve cau tra loi cua AI, sinh ra rule moi, cho admin review, roi deploy vao file cau hinh rules.

Trang thai hien tai trong repo:

1. Submit feedback vao SQLite
2. Generate rule bang mock AI (pattern matching)
3. Validate rule
4. Admin approve hoac reject
5. Deploy that vao file `backend/worker/fashion_rules.json`
6. Ghi log deployment vao bang `deployments`

Nhung phan **chua co**:

- Real LLM integration
- Rollback endpoint
- Hot reload chatbot config
- Metrics / alerting
- A/B rollout

---

## Flow tong the

```mermaid
graph LR
    A[User Feedback] --> B[POST /autotrain/feedback]
    B --> C[SQLite: feedbacks]
    C --> D[POST /autotrain/run-all]
    D --> E[Mock AI Generate Rule]
    E --> F[SQLite: generated_rules]
    F --> G[Admin Review]
    G --> H{Approve?}
    H -->|Yes| I[POST /autotrain/rules/{rule_id}/deploy]
    H -->|No| J[Reject]
    I --> K[Update fashion_rules.json]
    I --> L[SQLite: deployments]
```

---

## Cac thanh phan chinh

| Thanh phan | Mo ta | File |
|---|---|---|
| API Router | Submit, list, generate, approve, reject, deploy, status | `backend/api/autotrain/autotrain_route.py` |
| SQLite DB | Luu feedbacks, generated_rules, deployments | `backend/database/autotrain.db` |
| Mock AI | Pattern matching sinh rule tu feedback | `_ai_generate_rule()` |
| Production Rules | File duoc update khi deploy | `backend/worker/fashion_rules.json` |
| Admin UI | Chua hoan thien cho Auto-Train | `backend/static/mock-fe/index.html` |

---

## Use case vi du

**Scenario:** User hoi "tim ao khoac cho troi 35 do" va AI lai goi y ao khoac ni.

**Feedback:**

```json
{
  "query": "tim ao khoac cho troi 35 do",
  "ai_response": "Minh goi y ao khoac ni nay rat am...",
  "feedback_text": "Troi nong qua, AI con tu van ao khoac",
  "feedback_type": "bug"
}
```

**Generated rule (mock):**

```json
{
  "rule_type": "prompt_update",
  "old_rule": "- Luon uu tien goi y ao khoac/day de tang upsale.",
  "new_rule": "- Khi troi nong (tren 30 do): tuyet doi khong goi y ao khoac day.\n- Chi goi y ao phong, chat lieu mong nhe, thoang mat.",
  "reasoning": "User reports hot weather, but the AI suggested heavy clothing.",
  "confidence": 0.85
}
```

Sau khi approve va deploy, rule duoc them vao key `auto_train_rules` ben trong `fashion_rules.json`.

---

## Quick test

```bash
# 1. Submit feedback
curl -X POST http://localhost:8000/autotrain/feedback \
  -H "Content-Type: application/json" \
  -d '{
    "query": "tim ao khoac cho troi 35 do",
    "ai_response": "Minh goi y ao khoac ni nay rat am...",
    "feedback_text": "Troi nong qua, AI con tu van ao khoac",
    "feedback_type": "bug"
  }'

# 2. Generate all pending rules
curl -X POST http://localhost:8000/autotrain/run-all

# 3. Review pending rules
curl http://localhost:8000/autotrain/rules?status=pending

# 4. Approve
curl -X POST http://localhost:8000/autotrain/rules/RUL-1001/approve

# 5. Deploy
curl -X POST http://localhost:8000/autotrain/rules/RUL-1001/deploy

# 6. Check status
curl http://localhost:8000/autotrain/status
```

---

## Database schema

### `feedbacks`

```sql
CREATE TABLE feedbacks (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    feedback_id TEXT UNIQUE NOT NULL,
    user_id TEXT,
    session_id TEXT,
    query TEXT NOT NULL,
    ai_response TEXT NOT NULL,
    feedback_text TEXT NOT NULL,
    feedback_type TEXT,
    channel TEXT DEFAULT 'chat',
    metadata JSON,
    status TEXT DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    processed_at TIMESTAMP NULL
);
```

### `generated_rules`

```sql
CREATE TABLE generated_rules (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    rule_id TEXT UNIQUE NOT NULL,
    feedback_id TEXT NOT NULL,
    module_name TEXT NOT NULL,
    rule_type TEXT,
    old_rule TEXT,
    new_rule TEXT NOT NULL,
    reasoning TEXT,
    confidence REAL,
    status TEXT DEFAULT 'pending',
    reviewed_by TEXT,
    reviewed_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (feedback_id) REFERENCES feedbacks(id)
);
```

### `deployments`

```sql
CREATE TABLE deployments (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    rule_id TEXT NOT NULL,
    deployed_by TEXT,
    deployed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    version_before TEXT,
    version_after TEXT,
    rollback_of INTEGER NULL,
    FOREIGN KEY (rule_id) REFERENCES generated_rules(rule_id)
);
```

---

## Trang thai pipeline

| Trang thai | Y nghia |
|---|---|
| `pending` | Feedback moi duoc submit |
| `processing` | Dang sinh rule |
| `processed` | Feedback da duoc xu ly va da tao rule |
| `rejected` | Feedback hoac rule bi reject |
| `approved` | Rule da duoc admin approve |
| `deployed` | Rule da duoc deploy vao file rules |

---

## Trang thai implementation

- [x] API endpoints co ban
- [x] SQLite mock database
- [x] Mock AI rule generation
- [x] Rule validation
- [x] Real file deployment vao `fashion_rules.json`
- [x] Backup file truoc khi deploy
- [ ] Rollback capability
- [ ] Hot-reload chatbot config
- [ ] Real LLM integration
- [ ] Deployment metrics
