const { DocumentProcessorServiceClient } = require('@google-cloud/documentai');

// Configuration
const PROJECT_ID = 'cim-summarizer';
const LOCATION = 'us';

async function createProcessor() {
  console.log('Creating Document AI processor...');
  
  const client = new DocumentProcessorServiceClient();
  
  try {
    // Create a Document OCR processor using a known processor type
    console.log('Creating Document OCR processor...');
    const [operation] = await client.createProcessor({
      parent: `projects/${PROJECT_ID}/locations/${LOCATION}`,
      processor: {
        displayName: 'CIM Document Processor',
        type: 'projects/245796323861/locations/us/processorTypes/ocr-processor',
      },
    });
    
    const [processor] = await operation.promise();
    console.log(`✅ Created processor: ${processor.name}`);
    console.log(`Processor ID: ${processor.name.split('/').pop()}`);
    
    // Save processor ID to environment
    console.log('\nAdd this to your .env file:');
    console.log(`DOCUMENT_AI_PROCESSOR_ID=${processor.name.split('/').pop()}`);
    
    return processor.name.split('/').pop();
    
  } catch (error) {
    console.error('Error creating processor:', error.message);
    
    if (error.message.includes('already exists')) {
      console.log('Processor already exists. Listing existing processors...');
      
      const [processors] = await client.listProcessors({
        parent: `projects/${PROJECT_ID}/locations/${LOCATION}`,
      });
      
      processors.forEach(processor => {
        console.log(`- ${processor.name}: ${processor.displayName}`);
        console.log(`  ID: ${processor.name.split('/').pop()}`);
      });
      
      if (processors.length > 0) {
        const processorId = processors[0].name.split('/').pop();
        console.log(`\nUsing existing processor ID: ${processorId}`);
        console.log(`Add this to your .env file:`);
        console.log(`DOCUMENT_AI_PROCESSOR_ID=${processorId}`);
        return processorId;
      }
    }
    
    throw error;
  }
}

async function testProcessor(processorId) {
  console.log(`\nTesting processor: ${processorId}`);
  
  const client = new DocumentProcessorServiceClient();
  
  try {
    // Test with a simple document
    const processorPath = `projects/${PROJECT_ID}/locations/${LOCATION}/processors/${processorId}`;
    
    console.log('Processor is ready for use!');
    console.log(`Processor path: ${processorPath}`);
    
  } catch (error) {
    console.error('Error testing processor:', error.message);
  }
}

async function main() {
  try {
    const processorId = await createProcessor();
    await testProcessor(processorId);
  } catch (error) {
    console.error('Setup failed:', error);
  }
}

if (require.main === module) {
  main();
}

module.exports = { createProcessor, testProcessor }; 