import axios from 'axios'; import type { VesselData } from '../types'; const API_BASE_URL = 'https://services.marinetraffic.com/api/vesselmasterdata/v3'; // Get API key at request time to ensure window.env is populated const getApiKey = (): string | undefined => { if (typeof window !== 'undefined' && window.env?.MARINE_TRAFFIC_API_KEY) { return window.env.MARINE_TRAFFIC_API_KEY; } return import.meta.env.VITE_MARINE_TRAFFIC_API_KEY; }; export async function getVesselData(imo: string): Promise { const apiKey = getApiKey(); // Lazy evaluate at request time // For development, return mock data if no API key is present if (!apiKey) { console.warn('No API key found - using mock data'); return getMockVesselData(imo); } try { const response = await axios.get(API_BASE_URL, { params: { imo, apikey: apiKey, } }); if (!response.data || response.data.errors) { throw new Error('Vessel not found'); } const data = response.data[0]; // API returns an array return { imo: imo, vesselName: data.VESSEL_NAME || 'Unknown', type: data.SHIP_TYPE || 'Unknown', length: Number(data.LENGTH) || 0, width: Number(data.BREADTH) || 0, estimatedEnginePower: calculateEstimatedEnginePower( Number(data.LENGTH), Number(data.BREADTH), data.SHIP_TYPE ) }; } catch (error) { console.error('AIS API Error:', error); throw new Error('Failed to fetch vessel data. Please check your IMO number and try again.'); } } function calculateEstimatedEnginePower(length: number, width: number, type: string): number { // Simplified power estimation based on vessel dimensions const baselinePower = length * width * 5; // kW // Apply vessel type multiplier const typeMultiplier = { 'Yacht': 1.2, 'Passenger': 1.5, 'Cargo': 1.0, 'default': 1.0 }[type] || 1.0; return Math.round(baselinePower * typeMultiplier); } // Mock data for development function getMockVesselData(imo: string): VesselData { return { imo: imo, vesselName: "Sample Yacht", type: "Yacht", length: 50, width: 9, estimatedEnginePower: 2250 // 50 * 9 * 5 }; }