#!/usr/bin/env node
// Node.js 24+. Run on your server. Normal account credits/limits apply.
// 1. OSRM_API_KEY=... node delivery.mjs --addresses addresses.json > review.json
//    addresses.json: ["Depot address", "Customer address", ...] (2–4 strings).
//    Review every candidate. Prepare confirmed.json with the format below.
// 2. OSRM_API_KEY=... node delivery.mjs --confirmed confirmed.json
//    {"depot":[55.2708,25.2048],"stops":[[55.2796,25.1972],[55.2624,25.2175]],"vehicles":1}
// Arrays are longitude,latitude. No time windows, capacity, truck or live-traffic model.
import { readFile } from 'node:fs/promises';
const key = process.env.OSRM_API_KEY;
const [mode, file] = process.argv.slice(2);
if (!key || !file || !['--addresses', '--confirmed'].includes(mode)) {
  console.error('Set OSRM_API_KEY. Usage: node delivery.mjs --addresses addresses.json | --confirmed confirmed.json');
  process.exit(1);
}
async function api(path, body) {
  const response = await fetch(`https://osrmroute.com${path}`, {
    method: body ? 'POST' : 'GET',
    headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
    ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(35_000),
  });
  const data = await response.json().catch(() => ({}));
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${data.code || 'Request failed'}; request ID ${response.headers.get('x-request-id') || 'unavailable'}. No automatic retry.`);
  return data;
}
const validPoint = p => Array.isArray(p) && p.length === 2 && p.every(x => typeof x === 'number' && Number.isFinite(x)) && Math.abs(p[0]) <= 180 && Math.abs(p[1]) <= 90;
try {
  const input = JSON.parse(await readFile(file, 'utf8'));
  if (mode === '--addresses') {
    if (!Array.isArray(input) || input.length < 2 || input.length > 4 || input.some(q => typeof q !== 'string' || q.length < 2 || q.length > 200)) throw new Error('Use 2–4 address strings.');
    const review = [];
    for (const address of input) {
      const data = await api(`/api/1/geocode?${new URLSearchParams({ q: address, limit: '3' })}`);
      review.push({ address, candidates: data.hits || [], requires_human_review: true });
    }
    console.log(JSON.stringify({ stage: 'review_coordinates', review }, null, 2));
  } else {
    if (!validPoint(input.depot) || !Array.isArray(input.stops) || input.stops.length < 1 || input.stops.length > 3 || !input.stops.every(validPoint)
      || !Number.isInteger(input.vehicles) || input.vehicles < 1 || input.vehicles > 2) throw new Error('Use a confirmed depot, 1–3 confirmed stops and 1–2 vehicles (subject to plan).');
    const points = [input.depot, ...input.stops].map(p => p.join(',')).join(';');
    const matrix = await api(`/api/v1/osrm/table/v1/driving/${points}?annotations=duration,distance`);
    if (matrix.code !== 'Ok' || !matrix.durations?.length || matrix.durations.some(row => row.some(x => x == null))) throw new Error('Disconnected stops. Review coordinates before optimization.');
    const result = await api('/api/1/vrp', {
      vehicles: Array.from({ length: input.vehicles }, (_, i) => ({ vehicle_id: `vehicle-${i + 1}`, start: input.depot })),
      services: input.stops.map((location, i) => ({ id: `stop-${i + 1}`, location })),
    });
    if (result.status !== 'finished' || !result.solution?.routes) throw new Error('No completed route solution.');
    console.log(JSON.stringify({ stage: 'vehicle_routes', matrix_seconds: matrix.durations, result }, null, 2));
  }
} catch (error) { console.error(error.message); process.exitCode = 1; }
