# API Documentation - AI Study Assistant

## 📡 COMPLETE API REFERENCE

---

## 📋 OVERVIEW

This document provides comprehensive API documentation for the AI Study Assistant backend services, including authentication, content management, learning analytics, and AI-powered tutoring features.

---

## 🔐 AUTHENTICATION

### Base URL
```
Production: https://api.teachit.app
Staging: https://api-staging.teachit.app
Development: http://localhost:5001
```

### Authentication Methods
All API endpoints require authentication using Firebase ID tokens.

#### Request Headers
```http
Authorization: Bearer <firebase_id_token>
Content-Type: application/json
X-Request-ID: <unique_request_id>
```

#### Token Validation
```javascript
// Example token validation
const idToken = req.headers.authorization?.split('Bearer ')[1];
const decodedToken = await admin.auth().verifyIdToken(idToken);
const uid = decodedToken.uid;
```

---

## 👤 USER MANAGEMENT

### Sign Up
```http
POST /auth/signup
```

**Request Body:**
```json
{
  "email": "student@school.com",
  "password": "securePassword123",
  "role": "student",
  "schoolId": "school123",
  "profile": {
    "name": "John Doe",
    "grade": 10,
    "section": "A"
  }
}
```

**Response:**
```json
{
  "success": true,
  "user": {
    "uid": "user123",
    "email": "student@school.com",
    "role": "student",
    "profile": {
      "name": "John Doe",
      "grade": 10,
      "section": "A"
    },
    "createdAt": "2026-05-06T20:00:00Z"
  },
  "token": "firebase_id_token"
}
```

### Sign In
```http
POST /auth/signin
```

**Request Body:**
```json
{
  "email": "student@school.com",
  "password": "securePassword123"
}
```

**Response:**
```json
{
  "success": true,
  "user": {
    "uid": "user123",
    "email": "student@school.com",
    "role": "student",
    "profile": {
      "name": "John Doe",
      "grade": 10,
      "section": "A"
    }
  },
  "token": "firebase_id_token"
}
```

### Get User Profile
```http
GET /auth/profile
```

**Response:**
```json
{
  "success": true,
  "user": {
    "uid": "user123",
    "email": "student@school.com",
    "role": "student",
    "schoolId": "school123",
    "profile": {
      "name": "John Doe",
      "grade": 10,
      "section": "A",
      "avatar": "https://storage.googleapis.com/avatars/user123.jpg"
    },
    "preferences": {
      "language": "en",
      "theme": "light",
      "notifications": true
    }
  }
}
```

---

## 🤖 AI TUTORING

### Ask Tutor
```http
POST /tutor/ask
```

**Request Body:**
```json
{
  "query": "What is a derivative?",
  "mode": "EXPLANATION",
  "context": {
    "subject": "Mathematics",
    "currentTopic": "Calculus"
  },
  "studentInfo": {
    "level": 2,
    "grade": 10
  }
}
```

**Response:**
```json
{
  "success": true,
  "response": {
    "text": "A derivative is a concept that measures how a function changes as its input changes...",
    "sources": [
      {
        "chunkId": "chunk123",
        "title": "Introduction to Derivatives",
        "relevance": 0.95
      }
    ],
    "metadata": {
      "mode": "EXPLANATION",
      "responseTime": 1.2,
      "tokens": 156,
      "model": "claude-3-5-sonnet-20241022"
    }
  },
  "interactionId": "interaction123"
}
```

### Get Chat History
```http
GET /tutor/history?limit=20&offset=0
```

**Response:**
```json
{
  "success": true,
  "interactions": [
    {
      "id": "interaction123",
      "query": "What is a derivative?",
      "response": "A derivative is a concept...",
      "mode": "EXPLANATION",
      "timestamp": "2026-05-06T20:00:00Z",
      "feedback": {
        "rating": 5,
        "comment": "Very helpful!"
      }
    }
  ],
  "total": 45,
  "hasMore": true
}
```

### Submit Feedback
```http
POST /tutor/feedback
```

**Request Body:**
```json
{
  "interactionId": "interaction123",
  "rating": 5,
  "comment": "Very helpful explanation",
  "category": "content_quality"
}
```

**Response:**
```json
{
  "success": true,
  "feedbackId": "feedback123"
}
```

---

## 📚 CONTENT MANAGEMENT

### Upload Content
```http
POST /content/upload
```

**Request (multipart/form-data):**
```
file: [file_content]
fileName: "derivatives_lesson.pdf"
mimeType: "application/pdf"
metadata: {
  "subject": "Mathematics",
  "concept": "Derivatives",
  "difficulty": 0.6,
  "grade": 10,
  "language": "en"
}
```

**Response:**
```json
{
  "success": true,
  "contentId": "content123",
  "chunks": [
    {
      "id": "chunk123",
      "text": "A derivative measures the rate of change...",
      "metadata": {
        "concept": "Derivatives",
        "difficulty": 0.6,
        "quality": 0.85
      }
    }
  ],
  "processingTime": 2.3
}
```

### Get Content List
```http
GET /content/list?subject=Mathematics&concept=Derivatives&limit=10
```

**Response:**
```json
{
  "success": true,
  "content": [
    {
      "id": "content123",
      "title": "Introduction to Derivatives",
      "subject": "Mathematics",
      "concept": "Derivatives",
      "difficulty": 0.6,
      "grade": 10,
      "chunkCount": 12,
      "uploadedAt": "2026-05-06T20:00:00Z",
      "uploadedBy": "teacher123"
    }
  ],
  "total": 25,
  "hasMore": true
}
```

### Get Content Details
```http
GET /content/{contentId}
```

**Response:**
```json
{
  "success": true,
  "content": {
    "id": "content123",
    "title": "Introduction to Derivatives",
    "subject": "Mathematics",
    "concept": "Derivatives",
    "difficulty": 0.6,
    "grade": 10,
    "chunks": [
      {
        "id": "chunk123",
        "text": "A derivative measures the rate of change...",
        "metadata": {
          "concept": "Derivatives",
          "difficulty": 0.6,
          "quality": 0.85,
          "wordCount": 156
        }
      }
    ],
    "uploadedAt": "2026-05-06T20:00:00Z",
    "uploadedBy": "teacher123"
  }
}
```

---

## 📝 QUIZ SYSTEM

### Create Quiz
```http
POST /quiz/create
```

**Request Body:**
```json
{
  "title": "Derivatives Quiz",
  "subject": "Mathematics",
  "concept": "Derivatives",
  "grade": 10,
  "difficulty": 0.5,
  "questions": [
    {
      "type": "multiple_choice",
      "question": "What is the derivative of f(x) = x²?",
      "options": [
        "2x",
        "x",
        "2",
        "x²"
      ],
      "correctAnswer": 0,
      "explanation": "Using the power rule, the derivative of x² is 2x."
    }
  ],
  "timeLimit": 30,
  "passingScore": 70
}
```

**Response:**
```json
{
  "success": true,
  "quizId": "quiz123",
  "questions": [
    {
      "id": "question123",
      "type": "multiple_choice",
      "question": "What is the derivative of f(x) = x²?",
      "options": [
        "2x",
        "x",
        "2",
        "x²"
      ]
    }
  ]
}
```

### Start Quiz
```http
POST /quiz/{quizId}/start
```

**Response:**
```json
{
  "success": true,
  "attemptId": "attempt123",
  "quiz": {
    "id": "quiz123",
    "title": "Derivatives Quiz",
    "timeLimit": 30,
    "questionCount": 5
  },
  "questions": [
    {
      "id": "question123",
      "type": "multiple_choice",
      "question": "What is the derivative of f(x) = x²?",
      "options": [
        "2x",
        "x",
        "2",
        "x²"
      ]
    }
  ],
  "startedAt": "2026-05-06T20:00:00Z"
}
```

### Submit Quiz Answer
```http
POST /quiz/{attemptId}/answer
```

**Request Body:**
```json
{
  "questionId": "question123",
  "answer": 0,
  "timeSpent": 15
}
```

**Response:**
```json
{
  "success": true,
  "correct": true,
  "explanation": "Using the power rule, the derivative of x² is 2x.",
  "points": 10,
  "totalPoints": 50
}
```

### Complete Quiz
```http
POST /quiz/{attemptId}/complete
```

**Response:**
```json
{
  "success": true,
  "results": {
    "score": 85,
    "totalQuestions": 5,
    "correctAnswers": 4,
    "timeSpent": 180,
    "passed": true,
    "completedAt": "2026-05-06T20:03:00Z"
  },
  "recommendations": [
    {
      "concept": "Chain Rule",
      "reason": "Related to derivatives",
      "priority": "medium"
    }
  ]
}
```

---

## 📊 LEARNING ANALYTICS

### Get Learning State
```http
GET /analytics/learning-state
```

**Response:**
```json
{
  "success": true,
  "learningState": {
    "studentId": "student123",
    "adaptiveDifficulty": {
      "currentLevel": 2.3,
      "targetLevel": 3.0,
      "adjustmentFactor": 0.1
    },
    "conceptStates": [
      {
        "concept": "Derivatives",
        "mastery": 0.75,
        "confidence": 0.82,
        "lastInteraction": "2026-05-06T20:00:00Z",
        "interactions": 12,
        "correctAnswers": 9
      }
    ],
    "spacedRepetition": {
      "nextReviewDue": [
        {
          "concept": "Derivatives",
          "dueDate": "2026-05-08T20:00:00Z",
          "priority": "high"
        }
      ]
    },
    "metadata": {
      "totalInteractions": 45,
      "averageSessionTime": 15.2,
      "streak": 7,
      "lastActive": "2026-05-06T20:00:00Z"
    }
  }
}
```

### Update Learning State
```http
POST /analytics/learning-state
```

**Request Body:**
```json
{
  "concept": "Derivatives",
  "mastery": 0.8,
  "confidence": 0.85,
  "interaction": {
    "type": "quiz",
    "correct": true,
    "timeSpent": 30
  }
}
```

**Response:**
```json
{
  "success": true,
  "updated": true,
  "newMastery": 0.8,
  "recommendations": [
    {
      "action": "advance_difficulty",
      "reason": "High mastery achieved"
    }
  ]
}
```

### Get Progress Report
```http
GET /analytics/progress?period=week&subject=Mathematics
```

**Response:**
```json
{
  "success": true,
  "progress": {
    "period": "week",
    "subject": "Mathematics",
    "stats": {
      "totalSessions": 12,
      "totalTime": 180,
      "conceptsStudied": 5,
      "averageScore": 82,
      "improvement": 15
    },
    "dailyProgress": [
      {
        "date": "2026-05-06",
        "sessions": 2,
        "timeSpent": 30,
        "concepts": ["Derivatives"],
        "score": 85
      }
    ],
    "conceptProgress": [
      {
        "concept": "Derivatives",
        "mastery": 0.75,
        "improvement": 0.2,
        "timeSpent": 60
      }
    ]
  }
}
```

---

## 🏫 SCHOOL MANAGEMENT

### Get School Info
```http
GET /school/info
```

**Response:**
```json
{
  "success": true,
  "school": {
    "id": "school123",
    "name": "Escola Profissional de Vila do Conde",
    "settings": {
      "curriculum": ["Mathematics", "Science", "English"],
      "language": "en",
      "policies": {
        "allowExternalKnowledge": false,
        "fallbackMode": "partial_with_hint",
        "minRetrievalConfidence": 0.6
      }
    },
    "subscription": {
      "plan": "premium",
      "maxStudents": 1000,
      "maxTeachers": 50,
      "expiresAt": "2026-12-31T23:59:59Z"
    }
  }
}
```

### Get Students
```http
GET /school/students?grade=10&section=A
```

**Response:**
```json
{
  "success": true,
  "students": [
    {
      "uid": "student123",
      "name": "John Doe",
      "email": "john@school.com",
      "grade": 10,
      "section": "A",
      "progress": {
        "totalSessions": 45,
        "averageScore": 82,
        "lastActive": "2026-05-06T20:00:00Z"
      }
    }
  ],
  "total": 25
}
```

---

## 📈 TEACHER ANALYTICS

### Get Class Analytics
```http
GET /analytics/class?grade=10&section=A&period=month
```

**Response:**
```json
{
  "success": true,
  "analytics": {
    "period": "month",
    "classSize": 25,
    "activeStudents": 23,
    "totalSessions": 345,
    "averageScore": 78,
    "topConcepts": [
      {
        "concept": "Derivatives",
        "mastery": 0.72,
        "students": 20
      }
    ],
    "strugglingStudents": [
      {
        "studentId": "student456",
        "name": "Jane Smith",
        "averageScore": 65,
        "conceptsNeedingHelp": ["Chain Rule"]
      }
    ],
    "engagementMetrics": {
      "dailyActiveUsers": 18,
      "averageSessionTime": 12.5,
      "questionFrequency": 3.2
    }
  }
}
```

---

## 🔄 WEBHOOKS

### Webhook Events
The system supports webhooks for real-time notifications:

#### Event Types
- `user.created`
- `interaction.completed`
- `quiz.completed`
- `content.uploaded`
- `learning.state.updated`

#### Webhook Configuration
```http
POST /webhooks/configure
```

**Request Body:**
```json
{
  "url": "https://your-app.com/webhook",
  "events": ["interaction.completed", "quiz.completed"],
  "secret": "webhook_secret"
}
```

**Response:**
```json
{
  "success": true,
  "webhookId": "webhook123"
}
```

---

## ⚠️ ERROR HANDLING

### Error Response Format
```json
{
  "success": false,
  "error": {
    "code": "AUTHENTICATION_REQUIRED",
    "message": "Authentication token is required",
    "details": {
      "field": "authorization",
      "expected": "Bearer <token>"
    },
    "requestId": "req_123456"
  }
}
```

### Error Codes
| Code | HTTP Status | Description |
|------|-------------|-------------|
| AUTHENTICATION_REQUIRED | 401 | Firebase token required |
| INVALID_TOKEN | 401 | Invalid or expired token |
| PERMISSION_DENIED | 403 | Insufficient permissions |
| NOT_FOUND | 404 | Resource not found |
| VALIDATION_ERROR | 400 | Request validation failed |
| RATE_LIMIT_EXCEEDED | 429 | Too many requests |
| INTERNAL_ERROR | 500 | Server error |
| SERVICE_UNAVAILABLE | 503 | Service temporarily unavailable |

---

## 📊 RATE LIMITING

### Rate Limits
| Endpoint | Requests/Minute | Burst |
|----------|------------------|-------|
| /tutor/ask | 20 | 5 |
| /quiz/* | 30 | 10 |
| /content/* | 10 | 3 |
| /analytics/* | 50 | 15 |
| /auth/* | 100 | 20 |

### Rate Limit Headers
```http
X-RateLimit-Limit: 20
X-RateLimit-Remaining: 15
X-RateLimit-Reset: 1623456789
```

---

## 🔍 SEARCH AND FILTERING

### Query Parameters
Common parameters across endpoints:

- `limit`: Number of items to return (default: 20, max: 100)
- `offset`: Number of items to skip (default: 0)
- `sort`: Field to sort by
- `order`: Sort order (asc/desc, default: desc)
- `filter`: Filter criteria (JSON object)
- `search`: Search term

### Example Filter
```http
GET /content/list?filter={"subject":"Mathematics","difficulty":{"gte":0.5,"lte":0.8}}&sort=uploadedAt&order=desc&limit=10
```

---

## 📱 SDK EXAMPLES

### JavaScript/TypeScript
```typescript
import { TeachItAPI } from '@teachit/api-client';

const api = new TeachItAPI({
  baseURL: 'https://api.teachit.app',
  token: 'firebase_id_token'
});

// Ask tutor
const response = await api.tutor.ask({
  query: 'What is a derivative?',
  mode: 'EXPLANATION'
});

// Get learning state
const learningState = await api.analytics.getLearningState();
```

### Flutter/Dart
```dart
import 'package:teachit_api/teachit_api.dart';

final api = TeachItAPI(
  baseURL: 'https://api.teachit.app',
  token: 'firebase_id_token'
);

// Ask tutor
final response = await api.tutor.ask(
  query: 'What is a derivative?',
  mode: 'EXPLANATION',
);

// Get learning state
final learningState = await api.analytics.getLearningState();
```

### Python
```python
from teachit_api import TeachItAPI

api = TeachItAPI(
    base_url='https://api.teachit.app',
    token='firebase_id_token'
)

# Ask tutor
response = api.tutor.ask(
    query='What is a derivative?',
    mode='EXPLANATION'
)

# Get learning state
learning_state = api.analytics.get_learning_state()
```

---

## 🧪 TESTING

### Test Environment
- **URL**: https://api-test.teachit.app
- **Authentication**: Use test Firebase project
- **Rate Limits**: Disabled for testing

### Test Data
```http
POST /auth/test/login
```

**Response:**
```json
{
  "success": true,
  "token": "test_token",
  "user": {
    "uid": "test_user",
    "role": "student"
  }
}
```

---

## 📋 CHANGE LOG

### Version 1.0.0 (2026-05-06)
- Initial API release
- Authentication endpoints
- AI tutoring functionality
- Quiz system
- Learning analytics
- Content management

---

## 📞 SUPPORT

### API Support
- **Email**: api-support@teachit.app
- **Documentation**: https://docs.teachit.app
- **Status Page**: https://status.teachit.app

### Community
- **GitHub**: https://github.com/teachit/api
- **Discord**: https://discord.gg/teachit
- **Forum**: https://community.teachit.app

---

*Last Updated: 2026-05-06*
*Version: 1.0.0*
*API Team: Backend Development*
