/**
 * API Route: TransportTrackerAgent Pattern Detection
 * GET /api/agents/transport-tracker/patterns - Get detected inefficiency patterns
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getTransportTrackerAgent } from '../../../../lib/agents/TransportTrackerAgent';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'GET') {
    return res.status(405).json({ success: false, error: 'Method not allowed' });
  }

  try {
    const agent = getTransportTrackerAgent();
    const { severity, type } = req.query;

    let patterns = agent.getPatterns();

    // Filter by severity if provided
    if (severity && typeof severity === 'string') {
      const validSeverities = ['low', 'medium', 'high'];
      if (!validSeverities.includes(severity)) {
        return res.status(400).json({
          success: false,
          error: `Invalid severity. Valid values: ${validSeverities.join(', ')}`
        });
      }
      patterns = patterns.filter(p => p.severity === severity);
    }

    // Filter by type if provided
    if (type && typeof type === 'string') {
      const validTypes = ['inefficient_route', 'high_carbon', 'excessive_handling', 'cold_chain_break'];
      if (!validTypes.includes(type)) {
        return res.status(400).json({
          success: false,
          error: `Invalid type. Valid values: ${validTypes.join(', ')}`
        });
      }
      patterns = patterns.filter(p => p.type === type);
    }

    // Calculate summary statistics
    const summary = {
      total: patterns.length,
      bySeverity: {
        high: patterns.filter(p => p.severity === 'high').length,
        medium: patterns.filter(p => p.severity === 'medium').length,
        low: patterns.filter(p => p.severity === 'low').length
      },
      byType: {
        inefficient_route: patterns.filter(p => p.type === 'inefficient_route').length,
        high_carbon: patterns.filter(p => p.type === 'high_carbon').length,
        excessive_handling: patterns.filter(p => p.type === 'excessive_handling').length,
        cold_chain_break: patterns.filter(p => p.type === 'cold_chain_break').length
      },
      totalPotentialSavingsKg: patterns.reduce((sum, p) => sum + p.potentialSavingsKg, 0)
    };

    res.status(200).json({
      success: true,
      data: {
        patterns,
        summary,
        recommendations: generatePatternRecommendations(patterns)
      }
    });
  } catch (error: any) {
    console.error('Error fetching transport patterns:', error);
    res.status(500).json({ success: false, error: error.message || 'Internal server error' });
  }
}

/**
 * Generate actionable recommendations based on detected patterns
 */
function generatePatternRecommendations(patterns: any[]): string[] {
  const recommendations: string[] = [];

  const highCarbonCount = patterns.filter(p => p.type === 'high_carbon').length;
  const excessiveHandlingCount = patterns.filter(p => p.type === 'excessive_handling').length;
  const coldChainBreaks = patterns.filter(p => p.type === 'cold_chain_break').length;

  if (highCarbonCount > 3) {
    recommendations.push('Multiple high-carbon transport events detected. Consider implementing a fleet electrification program or partnering with eco-friendly logistics providers.');
  }

  if (excessiveHandlingCount > 2) {
    recommendations.push('Products are being handled too many times. Review supply chain to consolidate shipments and reduce touchpoints.');
  }

  if (coldChainBreaks > 0) {
    recommendations.push('Cold chain integrity issues detected. Implement temperature monitoring IoT devices and establish clear handoff protocols.');
  }

  const totalSavings = patterns.reduce((sum, p) => sum + p.potentialSavingsKg, 0);
  if (totalSavings > 100) {
    recommendations.push(`Addressing detected patterns could save approximately ${totalSavings.toFixed(1)} kg of CO2 emissions.`);
  }

  if (recommendations.length === 0) {
    recommendations.push('Transport patterns look healthy. Continue monitoring for optimization opportunities.');
  }

  return recommendations;
}
