main-integration-orchestrator.tsโข19.5 kB
/**
* Main Integration Orchestrator
* Task 4.1: Integration Orchestrator Development
*
* Coordinates all system components into a cohesive educational content generation system:
* - Phase 1: Infrastructure preservation (browser, auth, API)
* - Phase 2: Universal content generation (BaseAdapter, assessments, subject adapters)
* - Phase 3: Composer widget mapping (content-to-widget, images, flow optimization)
* - Complete end-to-end workflow orchestration
* - Error handling and graceful degradation
*/
// Phase 2 Imports
import { BaseAdapter } from '../content-generation/base-adapter';
import { AdapterFactory } from '../content-generation/adapter-factory';
import { AssessmentEngine } from '../content-generation/assessment-engine';
// Phase 3 Imports
import { ImageSelectionService } from '../services/image-selection-service';
import { EducationalImageMapper } from '../widget-mappers/educational-image-mapper';
import { EducationalFlowOptimizer } from '../services/educational-flow-optimizer';
import { Phase3WidgetOrchestrator } from './phase3-widget-orchestrator';
// Infrastructure Imports
import { BrowserAutomation } from '../infrastructure/browser-automation';
import { Authentication } from '../infrastructure/authentication';
import { ApiClient } from '../infrastructure/api-client';
interface EducationalRequest {
topic: string;
subject: string;
grade_level: string;
learning_objectives?: string[];
author: string;
target_duration?: number;
additional_requirements?: string;
}
interface SystemConfiguration {
jwt_token_path: string;
api_endpoint: string;
browser_settings: {
headless: boolean;
timeout: number;
};
output_settings: {
format: 'composer_json' | 'rdp_file' | 'both';
save_location: string;
};
}
interface IntegrationResult {
success: boolean;
composition_data: any;
composition_url?: string;
execution_time: number;
components_used: string[];
errors?: string[];
warnings?: string[];
metadata: {
phase1_status: 'success' | 'error';
phase2_status: 'success' | 'error';
phase3_status: 'success' | 'error';
infrastructure_status: 'success' | 'error';
};
}
export class MainIntegrationOrchestrator {
// Phase 2 Components
private baseAdapter: BaseAdapter;
private adapterFactory: AdapterFactory;
private assessmentEngine: AssessmentEngine;
// Phase 3 Components
private imageService: ImageSelectionService;
private imageMapper: EducationalImageMapper;
private flowOptimizer: EducationalFlowOptimizer;
private widgetOrchestrator: Phase3WidgetOrchestrator;
// Infrastructure Components
private browserAutomation: BrowserAutomation;
private authentication: Authentication;
private apiClient: ApiClient;
private configuration: SystemConfiguration;
private executionLog: string[] = [];
constructor(configuration: SystemConfiguration) {
this.configuration = configuration;
this.initializeComponents();
}
/**
* Initialize all system components
*/
private initializeComponents(): void {
this.log('๐ง Initializing Main Integration Orchestrator...');
try {
// Phase 2 Components
this.log('๐ Initializing Phase 2: Content Generation Components...');
this.baseAdapter = new BaseAdapter();
this.adapterFactory = new AdapterFactory();
this.assessmentEngine = new AssessmentEngine();
// Phase 3 Components
this.log('๐จ Initializing Phase 3: Widget Mapping Components...');
this.imageService = new ImageSelectionService();
this.imageMapper = new EducationalImageMapper();
this.flowOptimizer = new EducationalFlowOptimizer();
this.widgetOrchestrator = new Phase3WidgetOrchestrator();
// Infrastructure Components
this.log('๐๏ธ Initializing Phase 1: Infrastructure Components...');
this.browserAutomation = new BrowserAutomation();
this.authentication = new Authentication(this.configuration.jwt_token_path);
this.apiClient = new ApiClient();
this.log('โ
All components initialized successfully');
} catch (error) {
this.log(`โ Component initialization error: ${error.message}`);
throw new Error(`Failed to initialize system components: ${error.message}`);
}
}
/**
* Main orchestration method - coordinates entire system
*/
public async orchestrateEducationalComposition(
request: EducationalRequest
): Promise<IntegrationResult> {
const startTime = Date.now();
this.log('\n๐ Starting Educational Composition Orchestration...');
this.log(`๐ Request: ${request.topic} (${request.subject}, ${request.grade_level})`);
const result: IntegrationResult = {
success: false,
composition_data: null,
execution_time: 0,
components_used: [],
metadata: {
phase1_status: 'error',
phase2_status: 'error',
phase3_status: 'error',
infrastructure_status: 'error'
}
};
try {
// Step 1: Validate Infrastructure
this.log('\n๐ Step 1: Infrastructure Validation...');
await this.validateInfrastructure();
result.metadata.phase1_status = 'success';
result.components_used.push('infrastructure');
// Step 2: Generate Educational Content (Phase 2)
this.log('\n๐ Step 2: Educational Content Generation (Phase 2)...');
const phase2Output = await this.executePhase2ContentGeneration(request);
result.metadata.phase2_status = 'success';
result.components_used.push('content-generation', 'assessment-engine');
// Step 3: Transform to Composer Widgets (Phase 3)
this.log('\n๐ Step 3: Composer Widget Transformation (Phase 3)...');
const phase3Output = await this.executePhase3WidgetMapping(phase2Output, request);
result.metadata.phase3_status = 'success';
result.components_used.push('widget-mapping', 'image-selection', 'flow-optimization');
// Step 4: Save and Deploy Composition
this.log('\n๐ Step 4: Composition Deployment...');
const deploymentResult = await this.executeCompositionDeployment(phase3Output);
result.metadata.infrastructure_status = 'success';
result.components_used.push('browser-automation', 'api-client');
// Step 5: Finalize Result
result.success = true;
result.composition_data = phase3Output;
result.composition_url = deploymentResult.url;
result.execution_time = Date.now() - startTime;
this.log(`\n๐ Orchestration Complete! Duration: ${result.execution_time}ms`);
return result;
} catch (error) {
this.log(`\nโ Orchestration Error: ${error.message}`);
result.errors = [error.message];
result.execution_time = Date.now() - startTime;
// Attempt graceful degradation
return await this.handleGracefulDegradation(request, result, error);
}
}
/**
* Phase 1: Infrastructure Validation
*/
private async validateInfrastructure(): Promise<void> {
this.log('๐ Validating system infrastructure...');
// Validate JWT token availability
this.log('๐ Validating authentication...');
const authResult = await this.authentication.validateToken();
if (!authResult.valid) {
throw new Error(`Authentication validation failed: ${authResult.error}`);
}
this.log('โ
Authentication validated');
// Validate browser automation readiness
this.log('๐ Validating browser automation...');
const browserResult = await this.browserAutomation.validateSetup();
if (!browserResult.ready) {
throw new Error(`Browser automation not ready: ${browserResult.error}`);
}
this.log('โ
Browser automation ready');
// Validate API connectivity
this.log('๐ Validating API connectivity...');
const apiResult = await this.apiClient.validateConnection();
if (!apiResult.connected) {
throw new Error(`API connectivity failed: ${apiResult.error}`);
}
this.log('โ
API connectivity validated');
this.log('๐ฏ Infrastructure validation complete');
}
/**
* Phase 2: Educational Content Generation
*/
private async executePhase2ContentGeneration(
request: EducationalRequest
): Promise<any> {
this.log('๐ง Executing Phase 2: Educational Content Generation...');
// Step 2.1: Generate base educational content
this.log('๐ Generating base educational content...');
const baseContent = await this.generateBaseContent(request);
this.log(`โ
Base content generated: ${Object.keys(baseContent.components).length} components`);
// Step 2.2: Apply subject-specific enhancements
this.log('๐ฌ Applying subject-specific enhancements...');
const enhancedContent = await this.applySubjectEnhancements(baseContent, request);
this.log(`โ
Subject enhancements applied for ${request.subject}`);
// Step 2.3: Generate assessments
this.log('๐ Generating assessment components...');
const assessmentComponents = await this.generateAssessments(enhancedContent, request);
this.log(`โ
Assessments generated: ${assessmentComponents.quiz ? 'quiz' : ''} ${assessmentComponents.flashcards ? 'flashcards' : ''}`);
const phase2Output = {
baseContent: enhancedContent,
assessmentEngine: assessmentComponents,
subjectAdapters: enhancedContent.metadata || {}
};
this.log('๐ฏ Phase 2: Content Generation complete');
return phase2Output;
}
/**
* Phase 3: Composer Widget Mapping
*/
private async executePhase3WidgetMapping(
phase2Output: any,
request: EducationalRequest
): Promise<any> {
this.log('๐จ Executing Phase 3: Composer Widget Mapping...');
// Configure Phase 3 transformation
const phase3Configuration = {
subject: request.subject,
grade_level: request.grade_level,
topic: request.topic,
learning_objectives: request.learning_objectives || [`Aprender sobre ${request.topic}`],
author: request.author,
target_duration: request.target_duration || 50
};
// Execute complete widget orchestration
this.log('๐ผ Orchestrating widget transformation...');
const composerComposition = await this.widgetOrchestrator.orchestratePhase3Transformation(
phase2Output,
phase3Configuration
);
this.log(`โ
Widget orchestration complete: ${composerComposition.composition.elements.length} widgets generated`);
this.log('๐ฏ Phase 3: Widget Mapping complete');
return composerComposition;
}
/**
* Phase 4: Composition Deployment
*/
private async executeCompositionDeployment(composerComposition: any): Promise<{ url: string }> {
this.log('๐ Executing composition deployment...');
// Step 4.1: Prepare composition data
this.log('๐ฆ Preparing composition data...');
const compositionData = this.prepareCompositionData(composerComposition);
// Step 4.2: Launch browser automation
this.log('๐ Launching browser automation...');
await this.browserAutomation.initialize(this.configuration.browser_settings);
// Step 4.3: Authenticate and navigate
this.log('๐ Authenticating and navigating to Composer...');
await this.browserAutomation.authenticate(this.authentication.getToken());
await this.browserAutomation.navigateToComposer();
// Step 4.4: Execute composition creation
this.log('โจ Creating composition...');
const creationResult = await this.browserAutomation.createComposition(compositionData);
// Step 4.5: Save via API
this.log('๐พ Saving via API...');
const apiResult = await this.apiClient.saveComposition(compositionData, this.authentication.getToken());
this.log(`โ
Composition deployed successfully: ${creationResult.url}`);
return {
url: creationResult.url || apiResult.url
};
}
/**
* Generate base educational content using BaseAdapter
*/
private async generateBaseContent(request: EducationalRequest): Promise<any> {
const prompt = `Criar aula sobre ${request.topic} para ${request.grade_level} na disciplina de ${request.subject}`;
return await this.baseAdapter.generateEducationalContent(
prompt,
request.subject,
request.grade_level,
{
learningObjectives: request.learning_objectives,
additionalRequirements: request.additional_requirements
}
);
}
/**
* Apply subject-specific enhancements
*/
private async applySubjectEnhancements(baseContent: any, request: EducationalRequest): Promise<any> {
const subjectAdapter = this.adapterFactory.getAdapter(request.subject);
if (subjectAdapter) {
this.log(`๐ง Applying ${request.subject} specific enhancements...`);
return await subjectAdapter.enhanceContent(baseContent, {
gradeLevel: request.grade_level,
topic: request.topic
});
}
return baseContent;
}
/**
* Generate assessment components
*/
private async generateAssessments(content: any, request: EducationalRequest): Promise<any> {
return await this.assessmentEngine.generateComprehensiveAssessment(
content,
{
subject: request.subject,
gradeLevel: request.grade_level,
topic: request.topic,
assessmentTypes: ['quiz', 'flashcards']
}
);
}
/**
* Prepare composition data for deployment
*/
private prepareCompositionData(composerComposition: any): any {
// Add deployment metadata
return {
...composerComposition,
deployment: {
timestamp: new Date().toISOString(),
version: '4.0.0',
orchestrator: 'MainIntegrationOrchestrator'
}
};
}
/**
* Graceful degradation handling
*/
private async handleGracefulDegradation(
request: EducationalRequest,
result: IntegrationResult,
error: Error
): Promise<IntegrationResult> {
this.log('๐ก๏ธ Attempting graceful degradation...');
try {
// Attempt to provide fallback composition
if (result.metadata.phase2_status === 'success') {
this.log('๐ Phase 2 succeeded, attempting simplified Phase 3...');
// Create simplified composition
const simplifiedComposition = this.createFallbackComposition(request);
result.composition_data = simplifiedComposition;
result.warnings = [`Graceful degradation applied: ${error.message}`];
this.log('โ
Fallback composition created');
} else {
this.log('โ Phase 2 failed, creating minimal composition...');
result.composition_data = this.createMinimalComposition(request);
result.warnings = [`Minimal composition provided due to: ${error.message}`];
}
return result;
} catch (degradationError) {
this.log(`โ Graceful degradation failed: ${degradationError.message}`);
result.errors.push(`Degradation failed: ${degradationError.message}`);
return result;
}
}
/**
* Create fallback composition when Phase 3 fails
*/
private createFallbackComposition(request: EducationalRequest): any {
return {
composition: {
id: `fallback-${request.topic}-${Date.now()}`,
title: `${request.topic} - ${request.grade_level}`,
description: `Composiรงรฃo educacional simplificada sobre ${request.topic}`,
author: request.author,
created: new Date().toISOString().split('T')[0],
version: '4.0.0-fallback',
metadata: {
disciplina: request.subject,
serie: request.grade_level,
duracao_estimada: '50 minutos',
tags: [request.topic, request.subject, request.grade_level, 'fallback']
},
elements: [
{
id: 'fallback-header',
type: 'head-1',
content_title: 'Apresentaรงรฃo da Aula',
category: `๐ ${request.subject.toUpperCase()}`,
author_name: request.author
},
{
id: 'fallback-content',
type: 'text-1',
content_title: 'Conteรบdo Principal',
content: `<p>Esta รฉ uma composiรงรฃo educacional sobre ${request.topic} para ${request.grade_level}.</p>`
}
]
}
};
}
/**
* Create minimal composition when Phase 2 fails
*/
private createMinimalComposition(request: EducationalRequest): any {
return {
composition: {
id: `minimal-${Date.now()}`,
title: `Aula: ${request.topic}`,
description: 'Composiรงรฃo educacional mรญnima',
author: request.author,
created: new Date().toISOString().split('T')[0],
version: '4.0.0-minimal',
metadata: {
disciplina: request.subject,
serie: request.grade_level,
duracao_estimada: '50 minutos',
tags: [request.topic, 'minimal']
},
elements: [
{
id: 'minimal-content',
type: 'text-1',
content: `<h2>${request.topic}</h2><p>Conteรบdo educacional para ${request.grade_level}.</p>`
}
]
}
};
}
/**
* Logging utility
*/
private log(message: string): void {
const timestamp = new Date().toISOString();
const logEntry = `[${timestamp}] ${message}`;
this.executionLog.push(logEntry);
console.log(logEntry);
}
/**
* Get execution log for debugging
*/
public getExecutionLog(): string[] {
return [...this.executionLog];
}
/**
* System health check
*/
public async performHealthCheck(): Promise<{
overall_health: 'healthy' | 'degraded' | 'critical';
component_status: { [key: string]: 'ok' | 'warning' | 'error' };
recommendations: string[];
}> {
this.log('๐ฅ Performing system health check...');
const componentStatus: { [key: string]: 'ok' | 'warning' | 'error' } = {};
const recommendations: string[] = [];
try {
// Check Phase 2 Components
componentStatus.baseAdapter = 'ok';
componentStatus.assessmentEngine = 'ok';
// Check Phase 3 Components
componentStatus.imageService = 'ok';
componentStatus.flowOptimizer = 'ok';
// Check Infrastructure
const authStatus = await this.authentication.validateToken();
componentStatus.authentication = authStatus.valid ? 'ok' : 'error';
if (!authStatus.valid) {
recommendations.push('JWT token needs refresh or replacement');
}
// Determine overall health
const errorCount = Object.values(componentStatus).filter(status => status === 'error').length;
const warningCount = Object.values(componentStatus).filter(status => status === 'warning').length;
let overallHealth: 'healthy' | 'degraded' | 'critical';
if (errorCount === 0 && warningCount === 0) {
overallHealth = 'healthy';
} else if (errorCount === 0) {
overallHealth = 'degraded';
} else {
overallHealth = 'critical';
}
this.log(`๐ฏ Health check complete: ${overallHealth}`);
return {
overall_health: overallHealth,
component_status: componentStatus,
recommendations
};
} catch (error) {
this.log(`โ Health check failed: ${error.message}`);
return {
overall_health: 'critical',
component_status: { system: 'error' },
recommendations: ['System requires immediate attention', error.message]
};
}
}
}