# KTT LMS - AI Recommendation System Documentation

## Overview

The KTT LMS uses a **Hybrid Recommendation Engine** that combines three dimensions of analysis to provide personalized learning experiences:

1. **Rule-Based Logic** - If/then rules based on performance metrics
2. **Pattern Matching** - Learning style profiling and similar student patterns
3. **Behavioral Adaptation** - Real-time adjustments based on user behavior

---

## Types of AI Recommendations Currently Generated

### 1. Difficulty Level Recommendations

| Condition | Recommendation | Action |
|-----------|---------------|--------|
| Quiz score < 50% | `difficulty: easy` | Review fundamentals, slow down pace |
| Quiz score 50-80% | `difficulty: medium` | Maintain current pace |
| Quiz score > 80% | `difficulty: hard` | Accelerate, try advanced content |

**Example Output:**
```json
{
  "difficulty_level": "easy",
  "pace_suggestion": "slow_down",
  "reason": "Review fundamentals to strengthen understanding"
}
```

### 2. Learning Format Recommendations

Based on detected learning style:

| Learning Style | Preferred Format | AI Coach Adaptation |
|---------------|------------------|---------------------|
| **Visual** | Diagrams, charts, structured layouts | Uses ASCII diagrams, clear headings |
| **Practical** | Code examples, hands-on exercises | Leads with code, focuses on implementation |
| **Interactive** | Q&A dialogue, conversational | Asks Socratic questions, breaks into chunks |
| **Analytical** | Deep technical details | Explains the "why", uses terminology |

### 3. Topic-Based Recommendations

When weak topics are detected from quiz performance:

```json
{
  "next_topics": ["databases", "api-design", "authentication"],
  "actions": [{
    "type": "review_topics",
    "label": "Review Challenging Topics",
    "priority": "high"
  }]
}
```

### 4. Intervention Recommendations

Triggered when student appears to be struggling:

| Signal | Intervention |
|--------|-------------|
| Low quiz scores (<50%) | `intervention_needed: true` |
| High help-seeking (>10 AI questions) | Reduced confidence score, extra guidance |
| Low confidence level (<40%) | Encouragement messages, motivation boost |

### 5. Adaptive AI Chat Prompts

The AI coach dynamically adjusts its teaching style based on:

**For struggling students (quiz < 50%):**
```
LEVEL: Use simple language. Provide more analogies. Avoid jargon. Be extra encouraging.
```

**For advanced students (quiz > 80%):**
```
LEVEL: Use technical terminology freely. Discuss advanced topics and best practices.
```

**For specific weak topics:**
```
FOCUS: Student struggles with: databases, APIs. Provide extra explanation for these topics.
```

---

## How Recommendations Are Triggered

### 1. Section Completion
When a user completes a lecture section, the engine:
- Fetches user analytics
- Generates personalized recommendation
- Shows popup with next steps

### 2. Quiz Submission
After quiz completion:
- Analyzes topic-level performance
- Identifies weak areas
- Suggests review content

### 3. Real-Time Chat
During AI coaching conversations:
- Adapts system prompt based on profile
- Adjusts explanation complexity
- Provides targeted examples

---

## Data Sources for Recommendations

| Data Type | Source | Usage |
|-----------|--------|-------|
| Quiz Scores | `quiz_results` table | Difficulty adjustment |
| Learning Style | `learning_profiles` table | Format preference |
| Weak Topics | Quiz analytics | Topic suggestions |
| Behavior Logs | `behavior_logs` table | Engagement signals |
| Session Data | `user_sessions` table | Pace adjustment |
| Chat History | `chat_history` table | Help-seeking frequency |

---

## Confidence Scoring

The system calculates a **confidence score** (0-100) indicating how well the student is progressing:

```javascript
confidence = base_score
           + (quiz_performance * 0.4)
           + (engagement_level * 0.3)
           - (help_seeking * 0.2)
           + (completion_rate * 0.1)
```

This score influences:
- Recommendation aggressiveness
- Encouragement messaging
- Intervention triggers

---

## API Endpoints for Recommendations

### Get User Analytics
```
GET /api/analytics/user
Authorization: <token>
```

### Get Recommendations
```
GET /api/recommendations?lecture_id=1&section_id=5
Authorization: <token>
```

### Log Recommendation Action
```
POST /api/behavior
{
  "event_type": "recommendation_action",
  "event_data": {"followed": true}
}
```

---

## Frontend Integration

### JavaScript Classes

```javascript
// Initialize recommendation engine
const engine = new HybridRecommendationEngine();

// Get recommendation
const rec = await engine.generateRecommendation(lectureId, sectionId);

// Get adaptive AI prompt
const prompt = await engine.getAdaptiveSystemPrompt();

// Suggest next section
const next = await engine.suggestNextSection(currentSection);
```

### UI Components

```javascript
// Show recommendation popup
showRecommendationPopup(recommendation);

// Close popup
closeRecommendationPopup();
```

---

## Admin Dashboard Features

Administrators can view:

- **At-Risk Students** - Students with `intervention_needed: true`
- **Common Weak Topics** - Aggregate topic performance
- **Learning Style Distribution** - Visual/Practical/Interactive/Analytical breakdown
- **Engagement Trends** - Session duration, activity levels
- **Intervention History** - Applied interventions and outcomes

Access at: `/static_pages/admin_dashboard.html`

---

## Technical Architecture

```
+------------------+     +-----------------+     +------------------+
|  Lecture Pages   |---->|  Recommendations|---->|  Analytics API   |
|  (Frontend)      |     |  Engine (JS)    |     |  (Backend)       |
+------------------+     +-----------------+     +------------------+
                               |
                               v
                    +-----------------+
                    |   AI Chat       |
                    |   (Adaptive     |
                    |    Prompts)     |
                    +-----------------+
```

Files involved:
- `/assets/js/recommendations.js` - Client-side engine
- `/utils/analytics_engine.py` - Server-side analytics
- `/server.py` - API endpoints
- Lectures HTML - Integration points

---

## Current Recommendation Types Summary

| Type | Trigger | Output |
|------|---------|--------|
| Difficulty Adjustment | Quiz score | easy/medium/hard |
| Pace Suggestion | Performance trend | slow_down/maintain/accelerate |
| Format Preference | Learning style | text/visual/hands-on/interactive |
| Topic Focus | Weak areas | List of topics to review |
| Intervention Flag | Struggling signals | Boolean + suggested actions |
| Confidence Score | Multiple factors | 0-100 score |
| Adaptive Prompt | All analytics | Customized AI system prompt |

---

## Test Accounts

- **Admin**: admin@ktt.edu / admin123 (can view cohort analytics)
- **Demo Student**: demo@student.edu / demo123 (experience recommendations)
