# Education Module - Udemy-like Platform for AI Agents

This education module provides a complete solution for AI agents to offer educational content in a Udemy-like interface. It provides two main components:

1. **Teacher Interface**: For creating and managing educational content using AI-driven content generation
2. **Student Interface**: For accessing and learning from the educational content with progress tracking

## Features

### Teacher Features

- AI-driven course generation
- Course, section, lecture, and quiz management
- Content editing and customization
- Progress monitoring for students

### Student Features

- Course catalog with filtering and searching
- Learning interface with progress tracking
- Quiz taking with automatic assessment
- Course enrollment and completion tracking

## Architecture

The module follows a modern architecture with:

- Express.js backend with proper middleware and routing
- SQLite database for development (can be replaced with PostgreSQL for production)
- React/Next.js frontend with TailwindCSS
- H5P integration for interactive content

## Getting Started

### Prerequisites

- Node.js 18+
- npm or yarn

### Installation

1. Clone the repository
2. Install dependencies:

```bash
cd education-module
npm install
```

3. Create a `.env` file with the following variables:

```
PORT=3008
AI_API_KEY=your-openai-api-key
JWT_SECRET=your-jwt-secret
```

### Running the Development Server

Start the backend server:

```bash
npm run backend
```

Start the frontend development server:

```bash
npm run dev
```

## API Documentation

### Course Management

- `GET /api/courses/public` - Get all public courses
- `GET /api/courses/agent/:agentId` - Get all courses for an agent
- `GET /api/courses/:courseId` - Get a course by ID
- `POST /api/courses` - Create a new course
- `PUT /api/courses/:courseId` - Update a course
- `DELETE /api/courses/:courseId` - Delete a course

### AI Content Generation

- `POST /api/ai-content/generate-course` - Generate a course structure
- `POST /api/ai-content/generate-section/:courseId` - Generate a section
- `POST /api/ai-content/generate-and-save-course` - Generate and save a course

## Database Schema

The database includes the following main tables:

- `agents`: Represents the AI agents
- `students`: Stores student information
- `courses`: Stores course information
- `sections`: Stores section information
- `lectures`: Stores lecture content
- `quizzes`: Stores quiz information
- `quiz_questions`: Stores quiz questions
- `enrollments`: Tracks student enrollment in courses
- `progress`: Tracks student progress through lectures

## Integration with AI CMS

This education module is designed to integrate with an AI CMS. When a user creates an AI agent and enables the education module:

1. The agent owner becomes the "teacher"
2. The teacher can access the education module interface
3. The teacher can create courses using AI-driven content generation
4. Students can access the courses through a separate student interface

## H5P Integration

The module supports H5P content for interactive learning experiences. Teachers can create and embed H5P content in their lectures.

## Integration with External Systems

The education module is designed to be integrated into external systems, providing a Udemy-like educational platform that can be embedded in any application.

### Component Library Organization

The module now follows a comprehensive component library approach (Option 5), which provides multiple levels of abstraction:

1. **Complete page components** - Ready to use with minimal configuration
2. **Container components** - Handle data fetching and state
3. **Presentational components** - For custom UI assembly
4. **Hooks** - For custom logic implementation

This organization allows you to choose the level of control you need:

```typescript
import {
  // Complete page components
  TeacherDashboardPage, StudentDashboardPage,

  // Container components that handle data fetching
  CourseListContainer, CourseContentContainer,

  // UI components for custom assembly
  CourseCard, H5PContent,

  // Context providers for state management
  EducationProvider,

  // Hooks for custom logic
  useCourses, useAuth
} from '@your-package/education-module';
```

### Integration Options

#### Option 1: Use Complete Page Components

The easiest approach - just mount the pre-built pages:

```tsx
import { EducationProvider, TeacherDashboardPage } from '@your-package/education-module';

function App() {
  return (
    <EducationProvider apiBaseUrl="/api/education" isTeacher={true}>
      <TeacherDashboardPage />
    </EducationProvider>
  );
}
```

#### Option 2: Use Container Components

For more control over layout while delegating data fetching:

```tsx
import { EducationProvider, CourseListContainer } from '@your-package/education-module';

function CoursesPage() {
  return (
    <EducationProvider apiBaseUrl="/api/education">
      <div className="custom-layout">
        <h1>My Courses</h1>
        <CourseListContainer 
          showEnrolled={true} 
          onCourseClick={(courseId) => console.log(courseId)}
        />
      </div>
    </EducationProvider>
  );
}
```

#### Option 3: Use Individual Components and Hooks

For complete control over UI and data flow:

```tsx
import { useAuth, useCourses, CourseCard } from '@your-package/education-module';

function CustomCourseList() {
  const { courses, loading } = useCourses({ showPublic: true });
  
  if (loading) return <div>Loading...</div>;
  
  return (
    <div className="custom-grid">
      {courses.map(course => (
        <CourseCard 
          key={course.id} 
          course={course} 
          onClick={() => handleCourseSelection(course)}
        />
      ))}
    </div>
  );
}
```

#### Option 4: Using the Initialization Helper

For consistent configuration across components:

```tsx
import { initializeEducationModule, EducationProvider, TeacherDashboardPage } from '@your-package/education-module';

function App() {
  const educationModule = initializeEducationModule({
    apiBaseUrl: '/api/education',
    agentId: 'agent-123',
  });
  
  const teacherView = educationModule.createTeacherView();
  
  return (
    <EducationProvider {...teacherView.config}>
      <TeacherDashboardPage />
    </EducationProvider>
  );
}
```

### Backend Integration

To integrate the backend API into your system:

```typescript
// Import the initialize function
import { initializeEducationAPI, mountEducationAPI } from '@your-package/education-module/backend';
import express from 'express';

// Option 1: Create a standalone API
const app = express();
const educationAPI = await initializeEducationAPI({
  port: 3008,
  apiPrefix: '/api/education',
  dbPath: './data/education.sqlite',
  jwtSecret: process.env.JWT_SECRET,
  aiApiKey: process.env.OPENAI_API_KEY
});

// Mount the API on your Express app
app.use('/education', educationAPI);

// Option 2: Use the helper function for mounting
const app = express();
await mountEducationAPI(app, '/education', {
  dbPath: './data/education.sqlite',
  jwtSecret: process.env.JWT_SECRET
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
```

### Frontend Integration

To integrate the frontend components into your React application:

```tsx
import { 
  EducationModule, 
  TeacherDashboard, 
  StudentDashboard,
  CourseViewer,
  CourseCreator,
  H5PEditor,
  CourseCard 
} from '@your-package/education-module/frontend';

// Option 1: Use the complete education module
function App() {
  return (
    <div className="app">
      <EducationModule 
        apiBaseUrl="/api/education"
        agentId="agent-123"
        isTeacher={true}
        theme="light"
      />
    </div>
  );
}

// Option 2: Use standalone components
function CourseCatalog() {
  const courses = [/* Your courses */];
  
  return (
    <div className="catalog">
      {courses.map(course => (
        <CourseCard 
          key={course.id}
          course={course}
          onClick={() => handleCourseClick(course)}
        />
      ))}
    </div>
  );
}

// Option 3: Use specialized dashboard components
function TeacherApp() {
  return <TeacherDashboard apiBaseUrl="/api/education" />;
}

function StudentApp() {
  return <StudentDashboard apiBaseUrl="/api/education" />;
}

// Option 4: Course viewer/editor components
function ViewCourse({ courseId }) {
  return <CourseViewer courseId={courseId} apiBaseUrl="/api/education" />;
}

function EditCourse({ courseId }) {
  return <CourseCreator courseId={courseId} apiBaseUrl="/api/education" />;
}
```

### Configuration Options

#### Backend Configuration Options

| Option | Description | Default |
|--------|-------------|---------|
| port | Port to run the server on | 3008 |
| apiPrefix | Prefix for API routes | "/api" |
| dbPath | Path to SQLite database | "./data/education.sqlite" |
| jwtSecret | Secret for JWT authentication | "education-module-secret" |
| corsOptions | CORS configuration | { origin: "*" } |
| enableStaticFiles | Whether to serve static files | true |
| staticFilesPath | Path to static files | "./public" |
| aiApiKey | API key for AI services | process.env.AI_API_KEY |

#### Frontend Configuration Options

| Option | Description | Default |
|--------|-------------|---------|
| apiBaseUrl | Base URL for API requests | "/api" |
| initialCourses | Initial courses to display | [] |
| agentId | ID of the current agent | undefined |
| isTeacher | Whether user is a teacher | false |
| isStudent | Whether user is a student | false |
| currentUserId | ID of the current user | undefined |
| theme | UI theme ("light" or "dark") | "light" |
| disableStyles | Whether to disable included styles | false |

### Working with Data Models

The education module exports TypeScript interfaces for all data models:

```typescript
import { 
  Course, 
  Section, 
  Lecture, 
  Quiz, 
  QuizQuestion,
  Student,
  Enrollment
} from '@your-package/education-module/frontend';

// Use the interfaces in your code
const courseData: Course = {
  id: 'course-123',
  title: 'My New Course',
  description: 'A comprehensive course',
  // ...other required fields
};
```

### Using H5P Content

The education module includes components for creating and displaying H5P content:

```tsx
import { H5PEditor, H5PContent } from '@your-package/education-module/frontend';

// H5P Editor component
function CreateH5PContent() {
  return <H5PEditor apiBaseUrl="/api/education" />;
}

// H5P Content viewer
function ViewH5PContent({ contentId }) {
  return <H5PContent contentId={contentId} apiBaseUrl="/api/education" />;
}
```

### AI-Powered Content Generation

The module provides components for AI-generated educational content:

```tsx
import { 
  AICourseGenerator, 
  AIQuizGenerator 
} from '@your-package/education-module/frontend';

// Generate a course with AI
function GenerateCourse() {
  const handleGenerated = (course) => {
    console.log('Generated course:', course);
  };
  
  return (
    <AICourseGenerator 
      apiBaseUrl="/api/education"
      onGenerated={handleGenerated}
      topic="Machine Learning Basics"
    />
  );
}

// Generate a quiz with AI
function GenerateQuiz() {
  const handleGenerated = (quiz) => {
    console.log('Generated quiz:', quiz);
  };
  
  return (
    <AIQuizGenerator
      apiBaseUrl="/api/education"
      onGenerated={handleGenerated}
      content="Introduction to React hooks and their usage patterns"
    />
  );
}
```

## License

MIT
