import type { VesselData, CarbonEstimate, TripEstimate } from '../types';

// Constants for carbon calculations
const EMISSION_FACTOR = 3.206; // tons of CO₂ per ton of fuel
const FUEL_DENSITY = 0.85; // tons per m³ (or metric tons per kiloliter)
const GALLONS_TO_LITERS = 3.78541; // 1 US gallon = 3.78541 liters
const LITERS_TO_CUBIC_METERS = 0.001; // 1 liter = 0.001 m³

export function calculateTripCarbon(
  vesselData: VesselData,
  distance: number, // nautical miles
  speed: number, // knots
  fuelRateLitersPerHour: number // liters per hour
): TripEstimate {
  const tripHours = distance / speed;
  
  // Calculate total fuel consumption in liters
  const fuelConsumptionLiters = fuelRateLitersPerHour * tripHours;
  
  // Convert liters to tons for CO₂ calculation
  const fuelConsumptionTons = (fuelConsumptionLiters * LITERS_TO_CUBIC_METERS) * FUEL_DENSITY;
  
  // Calculate CO₂ emissions using the provided formula
  // ENM = F(V) * EF / V
  const fuelRateTonsPerHour = (fuelRateLitersPerHour * LITERS_TO_CUBIC_METERS) * FUEL_DENSITY;
  const emissionsPerNM = (fuelRateTonsPerHour * EMISSION_FACTOR) / speed;
  const totalEmissions = emissionsPerNM * distance;

  return {
    distance,
    duration: tripHours,
    fuelConsumption: Math.round(fuelConsumptionLiters),
    co2Emissions: Number(totalEmissions.toFixed(2))
  };
}

export function calculateCarbonFromFuel(fuelAmount: number, isGallons: boolean = false): number {
  // Convert to liters if input is in gallons
  const liters = isGallons ? fuelAmount * GALLONS_TO_LITERS : fuelAmount;
  
  // Convert liters to cubic meters (m³)
  const cubicMeters = liters * LITERS_TO_CUBIC_METERS;
  
  // Convert volume to mass (tons)
  const fuelTons = cubicMeters * FUEL_DENSITY;
  
  // Calculate CO₂ emissions
  const co2Emissions = fuelTons * EMISSION_FACTOR;
  
  return Number(co2Emissions.toFixed(2));
}

export function calculateCarbonFromDistance(distance: number): number {
  // This is a simplified calculation, consider removing or updating based on the new formula
  return calculateCarbonFromFuel(distance * 25); // 25 liters per nautical mile is a rough estimate
}