import OrchestrationService from '../services/OrchestrationService';

/**
 * Examples of using the OrchestrationService for complex translation workflows
 */

// Initialize the service with your API key
const apiKey = 'your-fluentc-site-uuid';
OrchestrationService.initialize(apiKey);

/**
 * Example 1: Smart Translation with Auto-Detection
 * Automatically detects language, determines best mode, and translates
 */
export async function smartTranslationExample() {
  try {
    const result = await OrchestrationService.smartTranslate({
      input: "Hello world! This is a test of the FluentC translation system.",
      targetLanguage: 'es',
      mode: 'auto', // Automatically chooses real-time or batch
      onProgress: (progress) => {
        console.log(`Step ${progress.step}/${progress.totalSteps}: ${progress.stepName}`);
      }
    });
    
    console.log('Smart Translation Result:', result);
    return result;
  } catch (error) {
    console.error('Smart translation failed:', error);
    throw error;
  }
}

/**
 * Example 2: Batch Translation of Multiple Items
 * Translates multiple pieces of content in parallel
 */
export async function batchTranslationExample() {
  const contentItems = [
    "Welcome to our website",
    "About us",
    "Contact information",
    "<h1>Products</h1><p>Discover our latest offerings</p>",
    "Terms and conditions apply"
  ];

  try {
    const result = await OrchestrationService.batchTranslate(contentItems, {
      targetLanguage: 'fr',
      sourceLanguage: 'en',
      inputFormat: 'text',
      maxParallel: 3,
      onProgress: (progress) => {
        console.log(`Batch Progress: ${progress.processedItems}/${progress.totalItems} completed`);
      },
      onItemComplete: (result) => {
        console.log(`Completed item ${result.index + 1}:`, result.result?.translation);
      }
    });

    console.log('Batch Translation Results:', result);
    return result;
  } catch (error) {
    console.error('Batch translation failed:', error);
    throw error;
  }
}

/**
 * Example 3: Complex Page Translation Workflow
 * Handles complete page translation with title, content, and metadata
 */
export async function pageTranslationExample() {
  try {
    const result = await OrchestrationService.translatePage({
      pageUrl: 'https://example.com/sample-page',
      targetLanguage: 'de',
      sourceLanguage: 'en',
      translateMetadata: true,
      onProgress: (progress) => {
        console.log(`Page Translation: ${progress.stepName} (${progress.step}/${progress.totalSteps})`);
      }
    });

    console.log('Page Translation Result:', result);
    return result;
  } catch (error) {
    console.error('Page translation failed:', error);
    throw error;
  }
}

/**
 * Example 4: Custom Workflow
 * Create a custom workflow for specific business logic
 */
export async function customWorkflowExample() {
  const customWorkflow = {
    steps: [
      {
        name: 'validate-input',
        action: 'custom',
        handler: async () => {
          // Custom validation logic
          const input = "Bonjour le monde!";
          if (input.length < 5) {
            throw new Error('Input too short');
          }
          return { validatedInput: input };
        },
        required: true
      },
      {
        name: 'detect-language',
        action: 'detectLanguage',
        params: (prevResults) => ({
          input: prevResults[0].validatedInput,
          inputFormat: 'text'
        }),
        required: true
      },
      {
        name: 'translate-to-multiple-languages',
        action: 'custom',
        handler: async (prevResults) => {
          const input = prevResults[0].validatedInput;
          const targetLanguages = ['en', 'es', 'de'];
          
          const translations = {};
          
          for (const lang of targetLanguages) {
            try {
              const result = await OrchestrationService.apiService.translateContent({
                input,
                inputFormat: 'text',
                targetLanguage: lang,
                mode: 'real-time'
              });
              translations[lang] = result.translation;
            } catch (error) {
              translations[lang] = { error: error.message };
            }
          }
          
          return { multipleTranslations: translations };
        },
        required: true
      }
    ],
    onProgress: (progress) => {
      console.log(`Custom Workflow: ${progress.stepName} (${progress.step}/${progress.totalSteps})`);
    },
    onComplete: (result) => {
      console.log('Custom workflow completed:', result);
    },
    onError: (error) => {
      console.error('Custom workflow failed:', error);
    }
  };

  try {
    const result = await OrchestrationService.executeWorkflow(customWorkflow);
    return result;
  } catch (error) {
    console.error('Custom workflow execution failed:', error);
    throw error;
  }
}

/**
 * Example 5: Error Handling and Recovery
 * Shows how to handle errors with retry logic
 */
export async function errorHandlingExample() {
  try {
    const result = await OrchestrationService.smartTranslate({
      input: "This is a test with error handling",
      targetLanguage: 'invalid-language-code', // This will cause an error
      maxRetries: 3,
      onProgress: (progress) => {
        console.log(`Progress: ${progress.stepName} - Status: ${progress.status}`);
      }
    });
    
    return result;
  } catch (error) {
    console.log('Expected error occurred:', error.message);
    
    // Retry with correct parameters
    console.log('Retrying with correct parameters...');
    
    const retryResult = await OrchestrationService.smartTranslate({
      input: "This is a test with error handling",
      targetLanguage: 'es',
      maxRetries: 3,
      onProgress: (progress) => {
        console.log(`Retry Progress: ${progress.stepName}`);
      }
    });
    
    console.log('Retry successful:', retryResult);
    return retryResult;
  }
}

/**
 * Example 6: Monitoring and Status Tracking
 * Shows how to monitor workflow progress and manage state
 */
export async function monitoringExample() {
  // Start a long-running workflow
  const workflowPromise = OrchestrationService.smartTranslate({
    input: "This is a long text that will be processed in batch mode because it's longer than 1000 characters. ".repeat(50),
    targetLanguage: 'es',
    mode: 'auto',
    onProgress: (progress) => {
      console.log(`Workflow Progress: ${progress.stepName} (${progress.step}/${progress.totalSteps})`);
      
      if (progress.status === 'polling') {
        console.log(`Polling attempt ${progress.progress?.attempt}, estimated wait: ${progress.progress?.estimatedWaitSeconds}s`);
      }
    }
  });

  // Monitor the workflow
  setTimeout(async () => {
    const workflowId = 'workflow_example'; // In real usage, you'd get this from the workflow
    const status = OrchestrationService.getWorkflowStatus(workflowId);
    if (status) {
      console.log('Current workflow status:', status);
    }
  }, 5000);

  try {
    const result = await workflowPromise;
    console.log('Long-running workflow completed:', result);
    return result;
  } catch (error) {
    console.error('Long-running workflow failed:', error);
    throw error;
  }
}

// Export all examples
export const examples = {
  smartTranslationExample,
  batchTranslationExample,
  pageTranslationExample,
  customWorkflowExample,
  errorHandlingExample,
  monitoringExample
};

// Example of how to run all examples
export async function runAllExamples() {
  console.log('=== OrchestrationService Examples ===\n');
  
  for (const [name, example] of Object.entries(examples)) {
    console.log(`\n--- Running ${name} ---`);
    try {
      await example();
      console.log(`✅ ${name} completed successfully`);
    } catch (error) {
      console.log(`❌ ${name} failed:`, error.message);
    }
  }
  
  // Cleanup old workflows
  OrchestrationService.cleanupWorkflows();
  console.log('\n=== All examples completed ===');
} 