# Ashlya Academy Backend Routes

This directory contains the modular API route blueprints for the Ashlya Academy backend. Each module handles specific functionality areas, providing a clean and organized structure for the API endpoints.

## 🏗️ Route Architecture

The routes are organized using Flask Blueprints, allowing for:
- **Modular Organization**: Each feature area has its own route file
- **Clean Separation**: Different concerns are isolated
- **Easy Maintenance**: Routes are easy to find and modify
- **Scalability**: New features can be added without affecting existing code

## 📁 Route Modules

### 🔐 Authentication Routes (`auth_routes.py`)
Handles user authentication and authorization:
- **Login/Logout**: User session management
- **Registration**: New user signup
- **Password Reset**: Forgot password functionality
- **Token Management**: JWT token operations
- **Google OAuth**: Social login integration

**Endpoints:**
```
POST /login          # User login
POST /signup         # User registration  
POST /logout         # User logout
POST /reset-pass     # Password reset
POST /google-login   # Google OAuth login
```

### 👤 User Routes (`user_routes.py`)
Manages user profiles and preferences:
- **Profile Management**: User profile CRUD operations
- **Preferences**: User settings and preferences
- **Dashboard Data**: User-specific dashboard information
- **Activity Tracking**: User activity monitoring

**Endpoints:**
```
GET  /profile        # Get user profile
POST /profile        # Update user profile
GET  /home           # User dashboard data
POST /preferences    # Update preferences
```

### 📚 Course Routes (`course_routes.py`)
Handles course management and discovery:
- **Course Listing**: Browse available courses
- **Course Details**: Detailed course information
- **Course Search**: Search and filter courses
- **Enrollment**: Course enrollment management
- **Mentor Profiles**: Instructor information

**Endpoints:**
```
GET  /course_home    # Course home page data
POST /search         # Course search
GET  /course-detail  # Course details
POST /enroll         # Course enrollment
GET  /mentor-detail  # Mentor profile
```

### 🎥 Video Routes (`video_routes.py`)
Manages video content and tracking:
- **Video Streaming**: Video content delivery
- **Progress Tracking**: Watch progress monitoring
- **Video Details**: Video metadata and information
- **Discussion**: Video-specific discussions

**Endpoints:**
```
GET  /get_videos     # List videos
GET  /video_detail   # Video details
POST /video_progress # Update watch progress
POST /discussion     # Video discussions
```

### 📝 Blog Routes (`blog_routes.py`)
Handles blog and content management:
- **Blog Listing**: Browse blog posts
- **Blog Details**: Individual blog post content
- **Category Management**: Blog categories
- **Tag System**: Blog tagging and filtering
- **Search**: Blog content search

**Endpoints:**
```
GET  /blogs          # List blog posts
GET  /blogs/{id}     # Blog post details
GET  /categories     # Blog categories
GET  /tags           # Popular tags
POST /search-blogs   # Search blog content
```

### 🤖 AI Chat Routes (`ai_chat_routes.py`)
Manages AI-powered interactions:
- **Chat Sessions**: AI conversation management
- **Message History**: Chat message storage
- **Context Management**: Conversation context
- **AI Responses**: Intelligent response generation

**Endpoints:**
```
POST /chat           # Send chat message
GET  /sessions       # Chat sessions
GET  /messages       # Chat history
DELETE /session      # Clear chat session
```

### 📊 Analytics Routes (`analytics_routes.py`)
Provides analytics and reporting:
- **User Analytics**: User behavior analysis
- **Course Analytics**: Course performance metrics
- **Engagement Metrics**: Platform engagement data
- **Reports**: Custom analytics reports

**Endpoints:**
```
GET  /user-analytics    # User analytics
GET  /course-analytics  # Course analytics
GET  /engagement        # Engagement metrics
POST /custom-report     # Generate custom reports
```

### ❓ Doubts Routes (`doubts_routes.py`)
Handles Q&A system:
- **Question Management**: Student questions
- **Answer System**: Expert answers
- **Discussion Threads**: Question discussions
- **Search**: Find relevant questions

**Endpoints:**
```
GET  /doubts         # List questions
POST /doubts         # Submit question
GET  /doubts/{id}    # Question details
POST /answer         # Submit answer
```

### 🧩 Quiz Routes (`quiz_routes.py`)
Manages assessments and quizzes:
- **Quiz Generation**: Dynamic quiz creation
- **Quiz Attempts**: Quiz taking and submission
- **Results**: Quiz results and scoring
- **Performance**: Quiz performance analytics

**Endpoints:**
```
GET  /quiz           # Get quiz
POST /submit-quiz    # Submit quiz answers
GET  /quiz-results   # Quiz results
GET  /quiz-stats     # Quiz statistics
```

## 🛠️ Route Implementation

### Blueprint Registration
Routes are registered as blueprints in the main application:

```python
# config/app_config.py
def register_blueprints(app):
    from routes.auth_routes import auth_bp
    from routes.user_routes import user_bp
    from routes.course_routes import course_bp
    from routes.video_routes import video_bp
    from routes.blog_routes import blog_bp
    from routes.ai_chat_routes import ai_chat_bp
    from routes.analytics_routes import analytics_bp
    from routes.doubts_routes import doubts_bp
    from routes.quiz_routes import quiz_bp
    
    app.register_blueprint(auth_bp, url_prefix='/api/auth')
    app.register_blueprint(user_bp, url_prefix='/api/user')
    app.register_blueprint(course_bp, url_prefix='/api/course')
    app.register_blueprint(video_bp, url_prefix='/api/video')
    app.register_blueprint(blog_bp, url_prefix='/api/blog')
    app.register_blueprint(ai_chat_bp, url_prefix='/api/ai')
    app.register_blueprint(analytics_bp, url_prefix='/api/analytics')
    app.register_blueprint(doubts_bp, url_prefix='/api/doubts')
    app.register_blueprint(quiz_bp, url_prefix='/api/quiz')
```

### Common Route Patterns

**Authentication Decorator**
```python
from utils import require_api_key

@route_bp.route('/endpoint', methods=['POST'])
@require_api_key
def protected_endpoint():
    # Route implementation
    pass
```

**Error Handling**
```python
from utils import create_error_response

@route_bp.route('/endpoint', methods=['GET'])
def endpoint():
    try:
        # Route logic
        return jsonify(result)
    except Exception as e:
        return create_error_response(str(e), 500)
```

**Response Formatting**
```python
from utils import format_api_response, add_keep_alive

@route_bp.route('/endpoint', methods=['GET'])
def endpoint():
    data = get_data()
    response = make_response(format_api_response(data))
    return add_keep_alive(response)
```

## 🔧 Route Utilities

### Common Utilities
Routes use shared utilities from the `utils` module:

- **`require_api_key`**: API key validation decorator
- **`add_keep_alive`**: Keep-alive header management
- **`format_api_response`**: Standardized response formatting
- **`create_error_response`**: Error response formatting
- **`encrypt_response`**: Response encryption (if enabled)

### Database Connections
Routes use the database connection manager:

```python
from utils import get_db_connection

@route_bp.route('/endpoint', methods=['POST'])
def endpoint():
    connection = get_db_connection()
    try:
        # Database operations
        pass
    finally:
        connection.close()
```

### Route Development Guidelines

1. **Use descriptive names**: Route functions should clearly indicate their purpose
2. **Include documentation**: Add docstrings for complex routes
3. **Handle errors gracefully**: Use try-catch blocks and return appropriate error responses
4. **Validate inputs**: Always validate request data before processing
5. **Follow security best practices**: Use authentication decorators where needed
6. **Maintain consistency**: Follow the established patterns for similar functionality

### Example Route Implementation
```python
@course_bp.route('/course-detail', methods=['POST'])
@require_api_key
def get_course_detail():
    """
    Get detailed information about a specific course.
    
    Expected JSON payload:
    {
        "course_id": int,
        "user_id": int (optional)
    }
    
    Returns:
    {
        "status": "success",
        "data": {
            "course": {...},
            "topics": [...],
            "instructor": {...}
        }
    }
    """
    try:
        data = request.get_json()
        
        # Validate required fields
        if 'course_id' not in data:
            return create_error_response('Course ID is required', 400)
        
        # Get course details
        course_detail = get_course_detail_logic(data['course_id'])
        
        # Format and return response
        response_data = format_api_response(course_detail)
        response = make_response(response_data)
        return add_keep_alive(response)
        
    except Exception as e:
        logger.error(f"Error in get_course_detail: {str(e)}")
        return create_error_response('Internal server error', 500)
```

### Caching
Routes implement caching where appropriate:

```python
from optimizations import cache_response

@route_bp.route('/cached-endpoint', methods=['GET'])
@require_api_key
@cache_response(timeout=300)  # 5-minute cache
def cached_endpoint():
    # Expensive operation
    return jsonify(data)
```

## 🔒 Security Considerations

### Input Validation
All routes validate input data:

```python
def validate_course_data(data):
    required_fields = ['title', 'description']
    for field in required_fields:
        if field not in data or not data[field]:
            return False, f"Missing required field: {field}"
    return True, "Valid"
```

### Rate Limiting
Routes implement rate limiting for protection:

```python
from optimizations import rate_limit

@route_bp.route('/api-endpoint', methods=['POST'])
@rate_limit(max_requests=100, per_minutes=60)
@require_api_key
def protected_endpoint():
    # Implementation
    pass
```

## 📚 Documentation

Each route module includes comprehensive documentation:
- **Purpose**: What the routes accomplish
- **Endpoints**: List of available endpoints
- **Parameters**: Expected request parameters
- **Responses**: Response format and examples
- **Error Codes**: Possible error responses
