// Simplified Browser-Compatible Processing Pipeline import type { StudentRequest, MatchResult, AIUpdate, AIInsight } from './types' // Simple browser-compatible processing export class SimpleBrowserProcessor { private processingQueue: StudentRequest[] = [] private isProcessing = false private subscribers: Set<(update: AIUpdate) => void> = new Set() // Add request to processing queue async addRequest(request: StudentRequest): Promise { this.processingQueue.push(request) console.log(`📋 Added request ${request.id} to processing queue`) // Start processing if not already running if (!this.isProcessing) { this.processQueue() } } // Subscribe to processing updates subscribe(callback: (update: AIUpdate) => void): () => void { this.subscribers.add(callback) return () => this.subscribers.delete(callback) } // Notify subscribers of updates private notify(update: AIUpdate): void { this.subscribers.forEach(callback => { try { callback(update) } catch (error) { console.error('Error in processing callback:', error) } }) } // Process the queue private async processQueue(): Promise { if (this.isProcessing || this.processingQueue.length === 0) { return } this.isProcessing = true console.log('🔄 Starting processing queue...') while (this.processingQueue.length > 0) { const request = this.processingQueue.shift()! try { this.notify({ type: 'request-processed', requestId: request.id, message: `Processing request for ${request.studentName}`, timestamp: new Date() }) // Mock AI processing with realistic delay await new Promise(resolve => setTimeout(resolve, 2000)) const matches = await this.mockAIMatching(request) this.notify({ type: 'request-processed', requestId: request.id, message: `Found ${matches.length} potential matches`, timestamp: new Date() }) } catch (error) { console.error('Error processing request:', error) this.notify({ type: 'alert', requestId: request.id, message: 'Processing failed', timestamp: new Date() }) } } this.isProcessing = false console.log('✅ Processing queue completed') } // Mock AI matching for browser demo private async mockAIMatching(request: StudentRequest): Promise { console.log(`🤖 AI processing: ${request.description}`) // Simulate AI analysis const categoryMatch = this.getCategoryMatch(request.category) const urgencyMultiplier = this.getUrgencyMultiplier(request.urgency) return [{ resourceId: `resource-${Date.now()}`, resourceName: categoryMatch.name, resourceType: this.mapCategoryToResourceType(request.category), confidenceScore: 0.75 + (Math.random() * 0.2), // 75-95% estimatedImpact: categoryMatch.impact * urgencyMultiplier, logisticalComplexity: categoryMatch.complexity, estimatedCost: categoryMatch.cost, fulfillmentTimeline: categoryMatch.timeline, reasoningFactors: [ 'AI-powered semantic analysis', `${request.category} category match`, `${request.urgency} urgency level`, 'Location compatibility verified' ], riskFactors: categoryMatch.risks }] } private getCategoryMatch(category: string) { const categoryData: Record = { 'clothing': { name: 'School Clothing Package', impact: 8.5, complexity: 2.0, cost: 60, timeline: '3-5 days', risks: ['Size verification needed', 'Seasonal appropriateness'] }, 'supplies': { name: 'Complete Supply Kit', impact: 9.0, complexity: 1.5, cost: 35, timeline: '1-2 days', risks: ['Grade-level appropriateness'] }, 'food': { name: 'Emergency Food Support', impact: 9.5, complexity: 3.0, cost: 45, timeline: '4-6 hours', risks: ['Dietary restrictions', 'Perishable items'] }, 'transportation': { name: 'Transport Assistance', impact: 7.5, complexity: 4.0, cost: 25, timeline: '1-3 days', risks: ['Schedule coordination', 'Safety verification'] }, 'emergency': { name: 'Emergency Response Package', impact: 10.0, complexity: 3.5, cost: 100, timeline: '2-4 hours', risks: ['Immediate availability', 'Specialized needs'] } } return categoryData[category] || categoryData['supplies'] } private getUrgencyMultiplier(urgency: string): number { const multipliers: Record = { 'low': 0.8, 'medium': 1.0, 'high': 1.3, 'critical': 1.6 } return multipliers[urgency] || 1.0 } private mapCategoryToResourceType(category: string): 'supplies' | 'clothing' | 'food' | 'transport' | 'emergency' | 'other' { const mapping: Record = { 'school-supplies': 'supplies', 'clothing': 'clothing', 'food': 'food', 'transportation': 'transport', 'emergency': 'emergency' } return mapping[category] || 'other' } // Generate insights for dashboard async generateInsights(requests: StudentRequest[]): Promise { const insights: AIInsight[] = [] // Category analysis const categoryCount = requests.reduce((acc, req) => { acc[req.category] = (acc[req.category] || 0) + 1 return acc }, {} as Record) const topCategory = Object.entries(categoryCount) .sort(([,a], [,b]) => b - a)[0] if (topCategory) { insights.push({ id: `insight-category-${Date.now()}`, type: 'trend', title: `High Demand: ${topCategory[0]}`, description: `${topCategory[1]} requests for ${topCategory[0]} in recent batch. Consider stocking additional resources.`, confidence: 0.85, severity: topCategory[1] > 3 ? 'medium' : 'low', timestamp: new Date() }) } // Urgency analysis const criticalCount = requests.filter(r => r.urgency.toString() === 'critical').length if (criticalCount > 0) { insights.push({ id: `insight-urgency-${Date.now()}`, type: 'recommendation', title: 'Critical Requests Detected', description: `${criticalCount} critical priority requests require immediate attention.`, confidence: 1.0, severity: 'high', timestamp: new Date() }) } return insights } } // Export singleton instance export const browserProcessor = new SimpleBrowserProcessor()