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
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
import { useQuery } from '@tanstack/react-query';
import type { VesselProfile } from '@/data/types';
import {
  getSanctionsScore,
  PORTFOLIO_SANCTIONS_HOLDINGS,
  type SanctionsExposureScore,
  type PortfolioSanctionsHolding,
} from '@/data/sanctions-network-data';
import {
  api,
  type PortCall,
  type RosterVessel,
  type SanctionsScreening,
  type VesselDetail,
  type VoyageEconomics,
} from '@/lib/api';

type ExceptionType =
  | 'route_deviation'
  | 'delay_risk'
  | 'port_congestion'
  | 'weather_disruption'
  | 'maintenance_risk'
  | 'fuel_anomaly'
  | 'schedule_variance'
  | 'security_alert'
  | 'ais_dark'
  | 'sanctions_match'
  | 'overdue_arrival'
  | 'inspection_failure';
type ExceptionSeverity = 'critical' | 'high' | 'watch' | 'normal';
type ExceptionStatus = 'active' | 'acknowledged' | 'resolved' | 'dismissed';
type MaintenanceType = 'scheduled' | 'emergency' | 'predictive' | 'regulatory';
type MaintenanceStatus = 'overdue' | 'due_soon' | 'scheduled' | 'in_progress' | 'completed';
type MaintenancePriority = 'critical' | 'high' | 'medium' | 'low';
type CharterType = 'time_charter' | 'voyage_charter' | 'spot' | 'bareboat';
type VoyageStatus = 'planned' | 'loading' | 'at_sea' | 'completed' | 'cancelled' | 'active';

function toExceptionType(val: string | null | undefined): ExceptionType {
  const valid: ExceptionType[] = [
    'route_deviation',
    'delay_risk',
    'port_congestion',
    'weather_disruption',
    'maintenance_risk',
    'fuel_anomaly',
    'schedule_variance',
    'security_alert',
    'ais_dark',
    'sanctions_match',
    'overdue_arrival',
    'inspection_failure',
  ];
  return val && valid.includes(val as ExceptionType) ? (val as ExceptionType) : 'route_deviation';
}

function toExceptionSeverity(val: string | null | undefined): ExceptionSeverity {
  const valid: ExceptionSeverity[] = ['critical', 'high', 'watch', 'normal'];
  return val && valid.includes(val as ExceptionSeverity) ? (val as ExceptionSeverity) : 'watch';
}

function toExceptionStatus(val: string | null | undefined): ExceptionStatus {
  const valid: ExceptionStatus[] = ['active', 'acknowledged', 'resolved', 'dismissed'];
  return val && valid.includes(val as ExceptionStatus) ? (val as ExceptionStatus) : 'active';
}

function toMaintenanceType(val: string | null | undefined): MaintenanceType {
  const valid: MaintenanceType[] = ['scheduled', 'emergency', 'predictive', 'regulatory'];
  return val && valid.includes(val as MaintenanceType) ? (val as MaintenanceType) : 'scheduled';
}

function toMaintenanceStatus(val: string | null | undefined): MaintenanceStatus {
  const valid: MaintenanceStatus[] = [
    'overdue',
    'due_soon',
    'scheduled',
    'in_progress',
    'completed',
  ];
  return val && valid.includes(val as MaintenanceStatus) ? (val as MaintenanceStatus) : 'scheduled';
}

function toMaintenancePriority(val: string | null | undefined): MaintenancePriority {
  const valid: MaintenancePriority[] = ['critical', 'high', 'medium', 'low'];
  return val && valid.includes(val as MaintenancePriority)
    ? (val as MaintenancePriority)
    : 'medium';
}

function toCharterType(val: string | null | undefined): CharterType {
  const valid: CharterType[] = ['time_charter', 'voyage_charter', 'spot', 'bareboat'];
  return val && valid.includes(val as CharterType) ? (val as CharterType) : 'spot';
}

function toVoyageStatus(val: string | null | undefined): VoyageStatus {
  const valid: VoyageStatus[] = ['planned', 'loading', 'at_sea', 'completed', 'cancelled'];
  return val && valid.includes(val as VoyageStatus) ? (val as VoyageStatus) : 'at_sea';
}

function mapStatusToProfile(apiStatus: string): VesselProfile['status'] {
  const map: Record<string, VesselProfile['status']> = {
    active: 'at_sea',
    at_sea: 'at_sea',
    in_port: 'in_port',
    anchored: 'anchored',
    maintenance: 'maintenance',
    decommissioned: 'maintenance',
  };
  return map[apiStatus] ?? 'at_sea';
}

function mapApiVesselToProfile(apiVessel: Record<string, unknown>): VesselProfile {
  return {
    id: apiVessel.id as number,
    name: (apiVessel.name as string) ?? 'Unknown Vessel',
    imo: (apiVessel.imo as string | null) ?? '—',
    mmsi: (apiVessel.mmsi as string | null) ?? '—',
    flag: (apiVessel.flag as string | null) ?? '—',
    type: (apiVessel.vesselType as string | null) ?? 'Cargo',
    status: mapStatusToProfile(apiVessel.status as string),
    yearBuilt: (apiVessel.yearBuilt as number | null) ?? 2000,
    utilization: 0,
    dwt: 0,
    gt: 0,
    loa: 0,
    beam: 0,
    draft: 0,
    engineType: '—',
    fuelConsumption: 0,
    currentPort: null,
    destination: null,
    eta: null,
    lat: null,
    lon: null,
    course: null,
    speed: null,
    nextServiceDue: null,
    classSociety: '—',
    owner: '—',
    operator: '—',
    charterer: null,
    charterType: null,
    charterRate: null,
    charterExpiry: null,
    insuranceExpiry: null,
    lastInspection: null,
    nextInspection: null,
    deficiencies: 0,
    detentions: 0,
    aiBriefing: null,
    riskScore: 0,
    complianceScore: 100,
    emissionsIntensity: 0,
  } as unknown as VesselProfile;
}

export function useVessels() {
  const {
    data: apiVessels = [],
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ['vessels'],
    queryFn: () => api.vessels.list(),
    refetchInterval: 300_000,
  });

  const isLive = apiVessels.length > 0;
  const vessels: VesselProfile[] = (apiVessels as Record<string, unknown>[]).map(
    mapApiVesselToProfile,
  );

  return { vessels, isLoading, error, isLive, refetch };
}

export function useVesselsDashboard() {
  return useQuery({
    queryKey: ['vessels-dashboard'],
    queryFn: () => api.dashboard(),
    refetchInterval: 300_000,
  });
}

export function useFleetExceptions(params?: { status?: string; severity?: string; type?: string }) {
  const {
    data: apiExceptions = [],
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ['fleet-exceptions', params],
    queryFn: () => api.exceptions.list(params),
    refetchInterval: 300_000,
  });

  const isLive = apiExceptions.length > 0;

  const fleetExceptions = apiExceptions.map((e: any) => ({
    id: String(e.id),
    type: toExceptionType(e.exceptionType as string | null | undefined),
    severity: toExceptionSeverity(e.severity as string | null | undefined),
    vesselId: (e.vesselId as number) ?? 0,
    vesselName: (e.vesselName as string) ?? `Vessel #${(e.vesselId as number) ?? 0}`,
    route: '—',
    title: (e.title as string) ?? '',
    description: (e.description as string) ?? '',
    whyItMatters: (e.whyItMatters as string) ?? '',
    recommendedResponse: (e.recommendedResponse as string) ?? '',
    businessConsequence: (e.businessConsequence as string) ?? '',
    owner: (e.owner as string) ?? '—',
    ownerFunction: (e.ownerFunction as string) ?? '—',
    detectedAt: (e.detectedAt as string) ?? '',
    acknowledgedAt: (e.acknowledgedAt as string | null) ?? null,
    resolvedAt: (e.resolvedAt as string | null) ?? null,
    status: toExceptionStatus(e.status as string | null | undefined),
    estimatedImpactUSD: parseFloat((e.estimatedImpactUsd as string) ?? '0'),
  }));

  return { fleetExceptions, isLoading, error, isLive, refetch };
}

export type VoyageRow = {
  voyageId: string;
  vesselId: number;
  vesselName: string;
  route: string;
  origin: string | null;
  destination: string | null;
  cargoType: string;
  estimatedRevenue: number;
  operatingCost: number;
  fuelCost: number;
  portCost: number;
  delayCost: number;
  marginEstimate: number;
  marginPct: number;
  tce: number;
  delayHours: number;
  charterType: CharterType;
  status: VoyageStatus;
  distanceNm: number;
  durationDays: number;
  performanceVsBudget?: number;
  voyageRef: string | null;
  vesselClass: string | null;
};

export function useVoyages() {
  // Use the new vessel_voyage_economics table which has real seeded data
  const {
    data: apiVoyages = [],
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ['voyage-economics'],
    queryFn: () => api.voyageEconomics.list(),
    refetchInterval: 120_000,
  });

  const isLive = apiVoyages.length > 0;

  const voyageEconomics: VoyageRow[] = (apiVoyages as VoyageEconomics[]).map((v) => {
    const grossRevenue = parseFloat(v.grossRevenue ?? '0');
    const totalCosts = parseFloat(v.totalCostsUsd ?? '0');
    const netMargin = parseFloat(v.netMarginUsd ?? '0');
    const marginPct = parseFloat(v.marginPct ?? '0');
    const tce = parseFloat(v.tcePerDay ?? '0');
    const delayHours = parseFloat(v.delayHours ?? '0');
    const delayCost = parseFloat(v.delayCostUsd ?? '0');
    return {
      voyageId: String(v.id),
      vesselId: v.vesselId,
      route: `${v.originPort}${v.destinationPort}`,
      origin: v.originPort,
      destination: v.destinationPort,
      cargoType: v.cargoType ?? '—',
      estimatedRevenue: grossRevenue,
      operatingCost: totalCosts,
      fuelCost: parseFloat(v.fuelCostUsd ?? '0'),
      portCost: parseFloat(v.portCostsUsd ?? '0'),
      delayCost: delayCost,
      marginEstimate: netMargin,
      marginPct: marginPct,
      tce: tce,
      delayHours: delayHours,
      charterType: toCharterType(v.charterType),
      status: toVoyageStatus(v.status),
      distanceNm: parseFloat(v.distanceNm ?? '0'),
      durationDays: parseFloat(v.durationDays ?? '0'),
      voyageRef: v.voyageRef,
      vesselName: v.vesselName ?? `Vessel #${v.vesselId}`,
      vesselClass: v.vesselClass ?? null,
    };
  });

  return { voyageEconomics, isLoading, error, isLive, refetch };
}

export function useVoyageEconomicsAnalytics() {
  return useQuery({
    queryKey: ['voyage-economics-analytics'],
    queryFn: () => api.voyageEconomics.analytics(),
    refetchInterval: 300_000,
  });
}

export function useMaintenance(params?: { status?: string; vesselId?: number }) {
  const {
    data: apiMaintenance = [],
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ['maintenance', params],
    queryFn: () => api.maintenance.list(params),
    refetchInterval: 120_000,
  });

  const isLive = apiMaintenance.length > 0;

  const maintenanceItems = apiMaintenance.map((m: any) => ({
    id: m.id as number,
    vesselId: m.vesselId as number,
    vesselName: (m.vesselName as string) ?? `Vessel #${m.vesselId as number}`,
    vesselType: m.vesselType as string | null,
    vesselFlag: m.vesselFlag as string | null,
    component: m.component as string,
    type: toMaintenanceType(m.maintenanceType as string | null | undefined),
    description: (m.description as string) ?? '',
    dueDate: (m.dueDate as string) ?? '',
    status: toMaintenanceStatus(m.status as string | null | undefined),
    priority: toMaintenancePriority(m.priority as string | null | undefined),
    estimatedCost: parseFloat((m.estimatedCost as string) ?? '0'),
    daysToDue: m.dueDate
      ? Math.round((new Date(m.dueDate as string).getTime() - Date.now()) / 86400000)
      : 999,
    riskOfServiceIssue: parseFloat((m.riskOfServiceIssue as string) ?? '0'),
    impactsVoyageAvailability: (m.impactsVoyageAvailability as boolean) ?? false,
    technician: (m.technician as string) ?? '—',
    assetHealth: parseFloat((m.assetHealth as string) ?? '75'),
    notes: m.notes as string | null,
  }));

  return { maintenanceItems, isLoading, error, isLive, refetch };
}

export function useSanctions(params?: { ofacStatus?: string }) {
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ['sanctions', params],
    queryFn: () => api.sanctions.list(params),
    refetchInterval: 300_000,
  });

  const isLive = (data?.length ?? 0) > 0;

  return { screenings: (data ?? []) as SanctionsScreening[], isLoading, error, isLive, refetch };
}

export function useSanctionsSummary() {
  return useQuery({
    queryKey: ['sanctions-summary'],
    queryFn: () => api.sanctions.summary(),
    refetchInterval: 300_000,
  });
}

export function usePortCalls(params?: { vesselId?: number }) {
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ['port-calls', params],
    queryFn: () => api.portCalls.list(params),
    refetchInterval: 120_000,
  });

  return { portCalls: (data ?? []) as PortCall[], isLoading, error, refetch };
}

export function usePerformanceMetrics() {
  const { vessels, isLoading: vLoading } = useVessels();
  const { voyageEconomics, isLoading: voyLoading } = useVoyages();

  const isLoading = vLoading || voyLoading;

  const performanceMetrics = vessels.map((v) => {
    const vesselVoyages = voyageEconomics.filter((voyage) => voyage.vesselId === v.id);
    const tce =
      vesselVoyages.length > 0
        ? vesselVoyages.reduce((s, voy) => s + voy.tce, 0) / vesselVoyages.length
        : 0;
    return {
      vesselId: v.id,
      vesselName: v.name,
      utilization: ((v as any).utilization as number) ?? 0,
      tce,
      fuelEfficiency: 0,
      onTimeArrivalRate: 0,
      avgDelayHours: 0,
      routeProfitability: 0,
      cargoTonnes: 0,
      revenuePerDay: 0,
    };
  });

  return { performanceMetrics, isLoading };
}

export function useRoster() {
  const { data, isLoading, error, refetch, isRefetching } = useQuery({
    queryKey: ['vessels-roster'],
    queryFn: () => api.roster(),
    refetchInterval: 60_000,
  });

  const isLive = (data?.length ?? 0) > 0;
  return {
    roster: (data ?? []) as RosterVessel[],
    isLoading,
    error,
    isLive,
    refetch,
    isRefetching,
  };
}

export function useVesselDetail(id: number) {
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ['vessel-detail', id],
    queryFn: () => api.vesselDetail(id),
    enabled: id > 0,
    refetchInterval: 60_000,
  });

  return { detail: (data ?? null) as VesselDetail | null, isLoading, error, refetch };
}

function mapApiToSanctionsScore(raw: Record<string, unknown>): SanctionsExposureScore {
  return {
    vesselId: raw.vesselId as string | number,
    score: (raw.score as number) ?? 0,
    tier: (raw.tier as SanctionsExposureScore['tier']) ?? 'clear',
    dataSource: (raw.dataSource as 'live' | 'modeled') ?? 'modeled',
    computedAt: (raw.computedAt as string) ?? new Date().toISOString(),
    rules: (raw.rules as SanctionsExposureScore['rules']) ?? [],
    networkNodes: (raw.networkNodes as SanctionsExposureScore['networkNodes']) ?? [],
    networkEdges: (raw.networkEdges as SanctionsExposureScore['networkEdges']) ?? [],
    summary: (raw.summary as string) ?? '',
  };
}

export function useSanctionsScore(vesselId: string | number) {
  const numId = typeof vesselId === 'string' ? parseInt(vesselId, 10) : vesselId;
  const { data, isLoading, error } = useQuery({
    queryKey: ['sanctions-score', vesselId],
    queryFn: () => api.sanctionsNetwork.score(numId),
    enabled: !!vesselId && !Number.isNaN(numId),
    staleTime: 30_000,
    retry: 1,
  });

  const apiScore = data ? mapApiToSanctionsScore(data) : null;
  const fallback = getSanctionsScore(vesselId);
  const sanctionsData = apiScore ?? fallback;

  return { sanctionsData, isLoading, error, isLive: !!apiScore };
}

function mapApiToPortfolioHolding(raw: Record<string, unknown>): PortfolioSanctionsHolding {
  return {
    vesselId: raw.vesselId as string | number,
    vesselName: (raw.vesselName as string) ?? `Vessel #${raw.vesselId}`,
    imo: (raw.imo as string) ?? '—',
    flag: (raw.flag as string) ?? 'UN',
    vesselType: (raw.vesselType as string) ?? 'Cargo',
    score: (raw.score as number) ?? 0,
    tier: (raw.tier as PortfolioSanctionsHolding['tier']) ?? 'clear',
    dataSource: (raw.dataSource as 'live' | 'modeled') ?? 'modeled',
    topRules: (raw.topRules as PortfolioSanctionsHolding['topRules']) ?? [],
    owner: (raw.owner as string) ?? '—',
    hullValue: (raw.hullValue as number) ?? 0,
    sanctionedNetworkNodes: (raw.sanctionedNetworkNodes as number) ?? 0,
    lastUpdated: (raw.lastUpdated as string) ?? new Date().toISOString(),
  };
}

export function useSanctionsPortfolio() {
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ['sanctions-portfolio'],
    queryFn: () => api.sanctionsNetwork.portfolio(),
    staleTime: 30_000,
    retry: 1,
  });

  let holdings: PortfolioSanctionsHolding[] = PORTFOLIO_SANCTIONS_HOLDINGS;
  let isLive = false;
  if (data && typeof data === 'object' && 'holdings' in data && Array.isArray((data as Record<string, unknown>).holdings)) {
    const apiHoldings = ((data as Record<string, unknown>).holdings as Record<string, unknown>[]).map(mapApiToPortfolioHolding);
    if (apiHoldings.length > 0) {
      holdings = apiHoldings;
      isLive = true;
    }
  }

  return { holdings, isLoading, error, isLive, refetch };
}