/**
 * Intake workflow definitions
 */

import type { OCRClient } from '@the-order/ocr';
import type { StorageClient } from '@the-order/storage';

export interface IntakeWorkflowInput {
  documentId: string;
  fileUrl: string;
  userId: string;
}

export interface IntakeWorkflowOutput {
  documentId: string;
  processed: boolean;
  classification: string;
  extractedData?: unknown;
  ocrText?: string;
}

/**
 * Intake workflow: ingestion → OCR → classify → route
 * 
 * This is a simplified implementation. In production, this would use
 * Temporal or AWS Step Functions for orchestration.
 */
export async function intakeWorkflow(
  input: IntakeWorkflowInput,
  ocrClient?: OCRClient,
  storageClient?: StorageClient
): Promise<IntakeWorkflowOutput> {
  // Step 1: Document ingestion (already done - file is in storage)
  
  // Step 2: OCR processing
  let ocrText = '';
  if (input.fileUrl && ocrClient && storageClient) {
    try {
      const ocrResult = await ocrClient.processFromStorage(input.fileUrl);
      ocrText = ocrResult.text;
    } catch (error) {
      // Fallback if OCR fails
      console.warn('OCR processing failed, using fallback:', error);
      ocrText = 'OCR processing unavailable';
    }
  }
  
  // Step 3: Classification
  const classification = classifyDocument(ocrText, input.fileUrl);
  
  // Step 4: Extract structured data
  const extractedData = extractData(ocrText, classification);
  
  // Step 5: Route to appropriate workflow
  // In production: await routeDocument(input.documentId, classification);
  
  return {
    documentId: input.documentId,
    processed: true,
    classification,
    extractedData: {
      ...extractedData,
      ocrText,
    },
    ocrText,
  };
}

/**
 * Classify document based on content and metadata
 */
function classifyDocument(content: string, _fileUrl?: string): string {
  // Simplified classification logic
  // In production, this would use ML models or rule-based classification
  
  const lowerContent = content.toLowerCase();
  
  if (lowerContent.includes('treaty') || lowerContent.includes('agreement')) {
    return 'treaty';
  }
  if (lowerContent.includes('legal') || lowerContent.includes('contract')) {
    return 'legal';
  }
  if (lowerContent.includes('payment') || lowerContent.includes('invoice')) {
    return 'finance';
  }
  if (lowerContent.includes('history') || lowerContent.includes('record')) {
    return 'history';
  }
  
  // Default classification
  return 'legal';
}

/**
 * Extract structured data from document
 */
function extractData(content: string, classification: string): Record<string, unknown> {
  // Simplified data extraction
  // In production, this would use NLP or structured extraction
  
  return {
    classification,
    wordCount: content.split(/\s+/).length,
    extractedAt: new Date().toISOString(),
  };
}

