/**
 * Risk Calculator Service
 *
 * Calculates a risk score (0-100) for shipments based on multiple factors.
 * Higher scores = higher risk of being late.
 *
 * Factors considered:
 * - Traffic congestion (0-10 scale in DB)
 * - Weather severity (0-1 scale in DB)
 * - Driver behavior score (0-1 scale, lower = riskier)
 * - Driver fatigue score (0-1 scale, higher = more fatigued)
 * - Route risk level (Low/Moderate/High)
 * - Time until scheduled arrival (less time = higher risk)
 */

// Weight each factor (should sum to 1.0)
const WEIGHTS = {
  traffic: 0.25,
  weather: 0.20,
  driverBehavior: 0.20,
  driverFatigue: 0.15,
  routeRisk: 0.10,
  timeBuffer: 0.10
};

/**
 * Calculate risk score for a single shipment
 * @param {Object} shipment - Shipment data with conditions and driver info
 * @returns {Object} - Risk score and breakdown
 */
function calculateRiskScore(shipment) {
  const breakdown = {};

  // Traffic: 0-10 → 0-100
  breakdown.traffic = (shipment.traffic_congestion_level / 10) * 100;

  // Weather: 0-1 → 0-100
  breakdown.weather = shipment.weather_severity * 100;

  // Driver behavior: 0-1 where 1 is good → invert so 0 is good
  breakdown.driverBehavior = (1 - shipment.behavior_score) * 100;

  // Driver fatigue: 0-1 where 1 is fatigued → 0-100
  breakdown.driverFatigue = shipment.fatigue_score * 100;

  // Route risk level: Low=0, Moderate=50, High=100
  const routeRiskMap = { 'Low': 0, 'Moderate': 50, 'High': 100 };
  breakdown.routeRisk = routeRiskMap[shipment.route_risk_level] || 50;

  // Time buffer: hours until scheduled arrival
  // Negative means already late, high positive means lots of buffer
  if (shipment.scheduled_arrival && shipment.actual_departure) {
    const now = new Date();
    const scheduled = new Date(shipment.scheduled_arrival);
    const hoursRemaining = (scheduled - now) / (1000 * 60 * 60);

    // More than 24 hours = low risk (0), already late = high risk (100)
    if (hoursRemaining < 0) {
      breakdown.timeBuffer = 100; // Already past due
    } else if (hoursRemaining > 24) {
      breakdown.timeBuffer = 0; // Plenty of time
    } else {
      breakdown.timeBuffer = ((24 - hoursRemaining) / 24) * 100;
    }
  } else {
    breakdown.timeBuffer = 50; // Default if we can't calculate
  }

  // Calculate weighted total
  const totalScore =
    breakdown.traffic * WEIGHTS.traffic +
    breakdown.weather * WEIGHTS.weather +
    breakdown.driverBehavior * WEIGHTS.driverBehavior +
    breakdown.driverFatigue * WEIGHTS.driverFatigue +
    breakdown.routeRisk * WEIGHTS.routeRisk +
    breakdown.timeBuffer * WEIGHTS.timeBuffer;

  return {
    score: Math.round(totalScore),
    riskLevel: getRiskLevel(totalScore),
    breakdown: {
      traffic: Math.round(breakdown.traffic),
      weather: Math.round(breakdown.weather),
      driverBehavior: Math.round(breakdown.driverBehavior),
      driverFatigue: Math.round(breakdown.driverFatigue),
      routeRisk: Math.round(breakdown.routeRisk),
      timeBuffer: Math.round(breakdown.timeBuffer)
    },
    weights: WEIGHTS
  };
}

/**
 * Convert numeric score to risk level category
 */
function getRiskLevel(score) {
  if (score >= 70) return 'High';
  if (score >= 40) return 'Moderate';
  return 'Low';
}

/**
 * Get risk level color for UI
 */
function getRiskColor(riskLevel) {
  const colors = {
    'High': '#e74c3c',
    'Moderate': '#f39c12',
    'Low': '#27ae60'
  };
  return colors[riskLevel] || '#95a5a6';
}

module.exports = {
  calculateRiskScore,
  getRiskLevel,
  getRiskColor,
  WEIGHTS
};
