import { logger } from '../utils/logger';
import { config } from '../config/env';
import { optimizedAgenticRAGProcessor } from './optimizedAgenticRAGProcessor';
import { documentAiProcessor } from './documentAiProcessor';
import { CIMReview } from './llmSchemas';

// Default empty CIMReview object
const defaultCIMReview: CIMReview = {
  dealOverview: {
    targetCompanyName: '',
    industrySector: '',
    geography: '',
    dealSource: '',
    transactionType: '',
    dateCIMReceived: '',
    dateReviewed: '',
    reviewers: '',
    cimPageCount: '',
    statedReasonForSale: '',
    employeeCount: ''
  },
  businessDescription: {
    coreOperationsSummary: '',
    keyProductsServices: '',
    uniqueValueProposition: '',
    customerBaseOverview: {
      keyCustomerSegments: '',
      customerConcentrationRisk: '',
      typicalContractLength: ''
    },
    keySupplierOverview: {
      dependenceConcentrationRisk: ''
    }
  },
  marketIndustryAnalysis: {
    estimatedMarketSize: '',
    estimatedMarketGrowthRate: '',
    keyIndustryTrends: '',
    competitiveLandscape: {
      keyCompetitors: '',
      targetMarketPosition: '',
      basisOfCompetition: ''
    },
    barriersToEntry: ''
  },
  financialSummary: {
    financials: {
      fy3: {
        revenue: '',
        revenueGrowth: '',
        grossProfit: '',
        grossMargin: '',
        ebitda: '',
        ebitdaMargin: ''
      },
      fy2: {
        revenue: '',
        revenueGrowth: '',
        grossProfit: '',
        grossMargin: '',
        ebitda: '',
        ebitdaMargin: ''
      },
      fy1: {
        revenue: '',
        revenueGrowth: '',
        grossProfit: '',
        grossMargin: '',
        ebitda: '',
        ebitdaMargin: ''
      },
      ltm: {
        revenue: '',
        revenueGrowth: '',
        grossProfit: '',
        grossMargin: '',
        ebitda: '',
        ebitdaMargin: ''
      }
    },
    qualityOfEarnings: '',
    revenueGrowthDrivers: '',
    marginStabilityAnalysis: '',
    capitalExpenditures: '',
    workingCapitalIntensity: '',
    freeCashFlowQuality: ''
  },
  managementTeamOverview: {
    keyLeaders: '',
    managementQualityAssessment: '',
    postTransactionIntentions: '',
    organizationalStructure: ''
  },
  preliminaryInvestmentThesis: {
    keyAttractions: '',
    potentialRisks: '',
    valueCreationLevers: '',
    alignmentWithFundStrategy: ''
  },
  keyQuestionsNextSteps: {
    criticalQuestions: '',
    missingInformation: '',
    preliminaryRecommendation: '',
    rationaleForRecommendation: '',
    proposedNextSteps: ''
  }
};

interface ProcessingResult {
  success: boolean;
  summary: string;
  analysisData: CIMReview;
  processingStrategy: 'document_ai_agentic_rag';
  processingTime: number;
  apiCalls: number;
  error: string | undefined;
}

class UnifiedDocumentProcessor {
  /**
   * Process document using Document AI + Agentic RAG strategy
   */
  async processDocument(
    documentId: string, 
    userId: string, 
    text: string,
    options: any = {}
  ): Promise<ProcessingResult> {
    const strategy = options.strategy || 'document_ai_agentic_rag';
    
    logger.info('Processing document with unified processor', {
      documentId,
      strategy,
      textLength: text.length
    });

    // Only support document_ai_agentic_rag strategy
    if (strategy === 'document_ai_agentic_rag') {
      return await this.processWithDocumentAiAgenticRag(documentId, userId, text, options);
    } else {
      throw new Error(`Unsupported processing strategy: ${strategy}. Only 'document_ai_agentic_rag' is supported.`);
    }
  }

  /**
   * Process document using Document AI + Agentic RAG approach
   */
  private async processWithDocumentAiAgenticRag(
    documentId: string, 
    userId: string, 
    text: string, 
    options: any
  ): Promise<ProcessingResult> {
    logger.info('Using Document AI + Agentic RAG processing strategy', { documentId });
    
    try {
      const startTime = Date.now();
      
      // Extract file buffer from options
      const { fileBuffer, fileName, mimeType } = options;
      
      if (!fileBuffer || !fileName || !mimeType) {
        throw new Error('Missing required options: fileBuffer, fileName, mimeType');
      }

      // Process with Document AI + Agentic RAG
      const result = await documentAiProcessor.processDocument(
        documentId,
        userId,
        fileBuffer,
        fileName,
        mimeType
      );

      const processingTime = Date.now() - startTime;

      if (result.success) {
        return {
          success: true,
          summary: result.content,
          analysisData: result.metadata?.agenticRagResult?.analysisData || {},
          processingStrategy: 'document_ai_agentic_rag',
          processingTime,
          apiCalls: result.metadata?.agenticRagResult?.apiCalls || 0,
          error: undefined
        };
      } else {
        return {
          success: false,
          summary: '',
          analysisData: defaultCIMReview,
          processingStrategy: 'document_ai_agentic_rag',
          processingTime,
          apiCalls: 0,
          error: result.error || 'Unknown processing error'
        };
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      logger.error('Document AI + Agentic RAG processing failed', { 
        documentId, 
        error: errorMessage 
      });
      
      return {
        success: false,
        summary: '',
        analysisData: defaultCIMReview,
        processingStrategy: 'document_ai_agentic_rag',
        processingTime: 0,
        apiCalls: 0,
        error: errorMessage
      };
    }
  }

  /**
   * Get processing statistics (simplified)
   */
  async getProcessingStats(): Promise<{
    totalDocuments: number;
    documentAiAgenticRagSuccess: number;
    averageProcessingTime: {
      documentAiAgenticRag: number;
    };
    averageApiCalls: {
      documentAiAgenticRag: number;
    };
  }> {
    // This would need to be implemented based on actual database queries
    // For now, return placeholder data
    return {
      totalDocuments: 0,
      documentAiAgenticRagSuccess: 0,
      averageProcessingTime: {
        documentAiAgenticRag: 0
      },
      averageApiCalls: {
        documentAiAgenticRag: 0
      }
    };
  }
}

export const unifiedDocumentProcessor = new UnifiedDocumentProcessor(); 