Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

29.9 KB
Raw Blame
import { readCappedJson } from '../../utils/cappedFetch';

// Open-Meteo sits on the request path as a third party: without a deadline a hung
// connection holds the caller until the socket gives up on its own. Every other
// outbound client in the codebase carries one.
const WEATHER_TIMEOUT_MS = 8000;

/**
 * Which slot of Open-Meteo's hourly series a HH:MM belongs to.
 *
 * The archive answers with one entry per hour of the requested day in the local
 * timezone, so the hour is the index. Anything unparseable means "no time given",
 * which falls back to the daily figures rather than guessing midnight.
 */
function hourIndexFromTime(time?: string): number | null {
  if (!time) return null;
  const m = /^(\d{1,2}):(\d{2})/.exec(time.trim());
  if (!m) return null;
  const hour = Number(m[1]);
  return Number.isInteger(hour) && hour >= 0 && hour <= 23 ? hour : null;
}

// A day of hourly series is a few kilobytes; a megabyte means the provider is
// misbehaving, not that the trip got longer.
const MAX_WEATHER_BYTES = 1024 * 1024;

/**
 * Open-Meteo GET with the shared deadline and the size cap.
 *
 * The body is read through the cap rather than buffered with .json(): Open-Meteo
 * answers chunked, so there is no content-length to check and a declared-length
 * test alone would let any amount of data through. The caller still gets the
 * response, because the status and `reason` are what shape its error.
 */
async function fetchOpenMeteo(url: string): Promise<{ response: Response; data: OpenMeteoForecast }> {
  const response = await fetch(url, { signal: AbortSignal.timeout(WEATHER_TIMEOUT_MS) });
  const data = await readCappedJson<OpenMeteoForecast>(response, MAX_WEATHER_BYTES);
  if (!data) {
    throw new ApiError(502, 'Open-Meteo API error');
  }
  return { response, data };
}

/**
 * lat/lng arrive as raw query strings and get interpolated straight into the
 * Open-Meteo URL. The MCP tool already coerces them with z.number(); the REST
 * route has no contract, so the boundary check lives here and covers both.
 */
function coord(value: string, max: number, label: string): number {
  // Number('') and Number('  ') are 0, which would silently geolocate the Gulf
  // of Guinea instead of failing, so an empty value is rejected outright.
  const n = String(value ?? '').trim() === '' ? Number.NaN : Number(value);
  if (!Number.isFinite(n) || Math.abs(n) > max) {
    throw new ApiError(400, `Invalid ${label}`);
  }
  return n;
}

// ── Interfaces ──────────────────────────────────────────────────────────

export interface WeatherResult {
  temp: number;
  temp_max?: number;
  temp_min?: number;
  main: string;
  description: string;
  type: string;
  sunrise?: string | null;
  sunset?: string | null;
  precipitation_sum?: number;
  precipitation_probability_max?: number;
  wind_max?: number;
  hourly?: HourlyEntry[];
  error?: string;
}

export interface HourlyEntry {
  hour: number;
  temp: number;
  precipitation: number;
  precipitation_probability: number;
  main: string;
  wind: number;
  humidity: number;
}

interface OpenMeteoForecast {
  error?: boolean;
  reason?: string;
  current?: { temperature_2m: number; weathercode: number };
  daily?: {
    time: string[];
    temperature_2m_max: number[];
    temperature_2m_min: number[];
    weathercode: number[];
    precipitation_sum?: number[];
    precipitation_probability_max?: number[];
    windspeed_10m_max?: number[];
    sunrise?: string[];
    sunset?: string[];
  };
  hourly?: {
    time: string[];
    temperature_2m: number[];
    precipitation_probability?: number[];
    precipitation?: number[];
    weathercode?: number[];
    windspeed_10m?: number[];
    relativehumidity_2m?: number[];
  };
}

// ── WMO code mappings ───────────────────────────────────────────────────

const WMO_MAP: Record<number, string> = {
  0: 'Clear',
  1: 'Clear',
  2: 'Clouds',
  3: 'Clouds',
  45: 'Fog',
  48: 'Fog',
  51: 'Drizzle',
  53: 'Drizzle',
  55: 'Drizzle',
  56: 'Drizzle',
  57: 'Drizzle',
  61: 'Rain',
  63: 'Rain',
  65: 'Rain',
  66: 'Rain',
  67: 'Rain',
  71: 'Snow',
  73: 'Snow',
  75: 'Snow',
  77: 'Snow',
  80: 'Rain',
  81: 'Rain',
  82: 'Rain',
  85: 'Snow',
  86: 'Snow',
  95: 'Thunderstorm',
  96: 'Thunderstorm',
  99: 'Thunderstorm',
};

const WMO_DESCRIPTION_DE: Record<number, string> = {
  0: 'Klar',
  1: 'Überwiegend klar',
  2: 'Teilweise bewölkt',
  3: 'Bewölkt',
  45: 'Nebel',
  48: 'Nebel mit Reif',
  51: 'Leichter Nieselregen',
  53: 'Nieselregen',
  55: 'Starker Nieselregen',
  56: 'Gefrierender Nieselregen',
  57: 'Starker gefr. Nieselregen',
  61: 'Leichter Regen',
  63: 'Regen',
  65: 'Starker Regen',
  66: 'Gefrierender Regen',
  67: 'Starker gefr. Regen',
  71: 'Leichter Schneefall',
  73: 'Schneefall',
  75: 'Starker Schneefall',
  77: 'Schneekörner',
  80: 'Leichte Regenschauer',
  81: 'Regenschauer',
  82: 'Starke Regenschauer',
  85: 'Leichte Schneeschauer',
  86: 'Starke Schneeschauer',
  95: 'Gewitter',
  96: 'Gewitter mit Hagel',
  99: 'Starkes Gewitter mit Hagel',
};

const WMO_DESCRIPTION_EN: Record<number, string> = {
  0: 'Clear sky',
  1: 'Mainly clear',
  2: 'Partly cloudy',
  3: 'Overcast',
  45: 'Fog',
  48: 'Rime fog',
  51: 'Light drizzle',
  53: 'Drizzle',
  55: 'Heavy drizzle',
  56: 'Freezing drizzle',
  57: 'Heavy freezing drizzle',
  61: 'Light rain',
  63: 'Rain',
  65: 'Heavy rain',
  66: 'Freezing rain',
  67: 'Heavy freezing rain',
  71: 'Light snowfall',
  73: 'Snowfall',
  75: 'Heavy snowfall',
  77: 'Snow grains',
  80: 'Light rain showers',
  81: 'Rain showers',
  82: 'Heavy rain showers',
  85: 'Light snow showers',
  86: 'Heavy snow showers',
  95: 'Thunderstorm',
  96: 'Thunderstorm with hail',
  99: 'Severe thunderstorm with hail',
};

// ── Cache management ────────────────────────────────────────────────────

const weatherCache = new Map<string, { data: WeatherResult; expiresAt: number }>();
const inFlight = new Map<string, Promise<WeatherResult>>();
const CACHE_MAX_ENTRIES = 1000;
const CACHE_PRUNE_TARGET = 500;
const CACHE_CLEANUP_INTERVAL = 5 * 60 * 1000; // 5 minutes

/** Drop expired entries, then trim the cache back if it is still over the cap. */
function pruneCache(): void {
  const now = Date.now();
  for (const [key, entry] of weatherCache) {
    if (now > entry.expiresAt) weatherCache.delete(key);
  }
  if (weatherCache.size > CACHE_MAX_ENTRIES) {
    const entries = [...weatherCache.entries()].sort((a, b) => a[1].expiresAt - b[1].expiresAt);
    const toDelete = entries.slice(0, entries.length - CACHE_PRUNE_TARGET);
    toDelete.forEach(([key]) => weatherCache.delete(key));
  }
}

let cleanupTimer: NodeJS.Timeout | null = null;

/**
 * Start the cache sweep. WeatherService calls this from onModuleInit.
 *
 * It used to be a bare setInterval at module scope, which meant every process
 * that so much as imported this file — including every test worker — started a
 * five-minute timer it never stopped. Nothing cleaned it up because there was
 * nothing to call.
 */
export function startCacheCleanup(): void {
  if (cleanupTimer) return;
  cleanupTimer = setInterval(pruneCache, CACHE_CLEANUP_INTERVAL);
  // Never hold the process open for a cache sweep.
  cleanupTimer.unref?.();
}

/** Stop the sweep (onModuleDestroy). Idempotent. */
export function stopCacheCleanup(): void {
  if (!cleanupTimer) return;
  clearInterval(cleanupTimer);
  cleanupTimer = null;
}

const TTL_FORECAST_MS = 60 * 60 * 1000; // 1 hour
const TTL_CURRENT_MS = 15 * 60 * 1000; // 15 minutes
const TTL_CLIMATE_MS = 24 * 60 * 60 * 1000; // 24 hours

export function cacheKey(lat: string, lng: string, date?: string, lang?: string): string {
  const rlat = Number.parseFloat(lat).toFixed(2);
  const rlng = Number.parseFloat(lng).toFixed(2);
  const base = `${rlat}_${rlng}_${date || 'current'}`;
  // Descriptions come back localized, so the language is part of the identity —
  // without it a cached German answer serves English callers for up to the TTL
  // (and the MCP tools default to 'en' while REST defaults to 'de', so the two
  // surfaces poisoned each other's descriptions).
  return lang ? `${base}_${lang}` : base;
}

function getCached(key: string): WeatherResult | null {
  const entry = weatherCache.get(key);
  if (!entry) return null;
  if (Date.now() > entry.expiresAt) {
    weatherCache.delete(key);
    return null;
  }
  return entry.data;
}

function setCache(key: string, data: WeatherResult, ttlMs: number): void {
  weatherCache.set(key, { data, expiresAt: Date.now() + ttlMs });
}

// ── Helpers ─────────────────────────────────────────────────────────────

export function estimateCondition(tempAvg: number, precipMm: number): string {
  if (precipMm > 5) return tempAvg <= 0 ? 'Snow' : 'Rain';
  if (precipMm > 1) return tempAvg <= 0 ? 'Snow' : 'Drizzle';
  if (precipMm > 0.3) return 'Clouds';
  return tempAvg > 15 ? 'Clear' : 'Clouds';
}

/**
 * Daily figures for a recent date via the forecast API's `past_days` window.
 *
 * The ERA5 archive lags roughly five days behind real time, so the last days of
 * an ongoing trip — and a location-local "yesterday" that has already slipped
 * out of the forward window in the server's UTC frame — answered with nulls,
 * rendered as a dash (#2167). The forecast model still carries those days.
 * Returns null when the requested date is not in the answered series, so the
 * caller can fall back to the archive.
 */
async function fetchRecentPastForecast(
  lat: string,
  lng: string,
  dateStr: string,
  lang: string,
): Promise<WeatherResult | null> {
  const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}&daily=temperature_2m_max,temperature_2m_min,weathercode&timezone=auto&past_days=5&forecast_days=2`;
  const { response, data } = await fetchOpenMeteo(url);

  if (!response.ok || data.error) {
    throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error');
  }

  const idx = (data.daily?.time || []).indexOf(dateStr);
  if (idx === -1 || data.daily!.temperature_2m_max[idx] == null || data.daily!.temperature_2m_min[idx] == null) {
    return null;
  }

  const code = data.daily!.weathercode[idx];
  const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN;
  return {
    temp: Math.round((data.daily!.temperature_2m_max[idx] + data.daily!.temperature_2m_min[idx]) / 2),
    temp_max: Math.round(data.daily!.temperature_2m_max[idx]),
    temp_min: Math.round(data.daily!.temperature_2m_min[idx]),
    main: WMO_MAP[code] || 'Clouds',
    description: descriptions[code] || '',
    type: 'forecast',
  };
}

// ── getWeather ──────────────────────────────────────────────────────────

async function _getWeatherImpl(
  lat: string,
  lng: string,
  date: string | undefined,
  lang: string,
  time?: string,
): Promise<WeatherResult> {
  const ck = cacheKey(lat, lng, date ? `${date}T${time ?? ''}` : date, lang);

  if (date) {
    const cached = getCached(ck);
    if (cached) return cached;

    const targetDate = new Date(date);
    const now = new Date();
    const diffDays = (targetDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24);

    // Forecast range (-1 .. +16 days)
    if (diffDays >= -1 && diffDays <= 16) {
      const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}&daily=temperature_2m_max,temperature_2m_min,weathercode&timezone=auto&forecast_days=16`;
      const { response, data } = await fetchOpenMeteo(url);

      if (!response.ok || data.error) {
        throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error');
      }

      const dateStr = targetDate.toISOString().slice(0, 10);
      const idx = (data.daily?.time || []).indexOf(dateStr);

      if (idx !== -1) {
        const code = data.daily!.weathercode[idx];
        const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN;

        const result: WeatherResult = {
          temp: Math.round((data.daily!.temperature_2m_max[idx] + data.daily!.temperature_2m_min[idx]) / 2),
          temp_max: Math.round(data.daily!.temperature_2m_max[idx]),
          temp_min: Math.round(data.daily!.temperature_2m_min[idx]),
          main: WMO_MAP[code] || 'Clouds',
          description: descriptions[code] || '',
          type: 'forecast',
        };

        setCache(ck, result, TTL_FORECAST_MS);
        return result;
      }

      // idx === -1 with diffDays <= 0: a location-local yesterday (or today in
      // the hours after the UTC rollover) that the forward window no longer
      // carries. Last year's climate is the wrong answer for a day that just
      // happened — ask the model's past_days window before falling through.
      if (diffDays <= 0) {
        const recent = await fetchRecentPastForecast(lat, lng, dateStr, lang);
        if (recent) {
          setCache(ck, recent, TTL_FORECAST_MS);
          return recent;
        }
      }
    }

    // Recent past inside the archive's lag window: the forecast API still has
    // real daily figures where ERA5 answers nulls. A request with a usable time
    // stays on the archive — only it has the hourly series a journal entry
    // wants (#1614). On a miss the archive below remains the fallback.
    if (diffDays < -1 && diffDays >= -5 && hourIndexFromTime(time) == null) {
      const dateStr = targetDate.toISOString().slice(0, 10);
      const recent = await fetchRecentPastForecast(lat, lng, dateStr, lang);
      if (recent) {
        setCache(ck, recent, TTL_CLIMATE_MS);
        return recent;
      }
    }

    // Past date: use archive API for the actual date
    if (diffDays < -1) {
      const dateStr = targetDate.toISOString().slice(0, 10);
      // With a time in hand, ask for the hourly series too: a journal entry made at
      // 14:30 wants the weather of that hour, not the day's high and low averaged
      // together, which is what a rainy morning and a bright afternoon collapse to.
      const hourParam = hourIndexFromTime(time) != null ? '&hourly=temperature_2m,weathercode' : '';
      const url = `https://archive-api.open-meteo.com/v1/archive?latitude=${lat}&longitude=${lng}&start_date=${dateStr}&end_date=${dateStr}&daily=temperature_2m_max,temperature_2m_min,weathercode,precipitation_sum${hourParam}&timezone=auto`;
      const { response, data } = await fetchOpenMeteo(url);

      if (!response.ok || data.error) {
        throw new ApiError(response.status || 500, data.reason || 'Open-Meteo Archive API error');
      }

      const hourIdx = hourIndexFromTime(time);
      const hourly = (data as { hourly?: { temperature_2m?: (number | null)[]; weathercode?: (number | null)[] } })
        .hourly;
      if (hourIdx != null && hourly?.temperature_2m?.[hourIdx] != null) {
        const temp = hourly.temperature_2m[hourIdx]!;
        const code = hourly.weathercode?.[hourIdx] ?? undefined;
        const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN;
        const result: WeatherResult = {
          temp: Math.round(temp),
          main: WMO_MAP[code!] || estimateCondition(temp, 0),
          description: descriptions[code!] || '',
          type: 'forecast',
        };
        setCache(ck, result, TTL_CLIMATE_MS);
        return result;
      }

      const daily = data.daily;
      if (daily && daily.time && daily.time.length > 0 && daily.temperature_2m_max[0] != null) {
        const code = daily.weathercode?.[0];
        const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN;
        const tMax = daily.temperature_2m_max[0];
        const tMin = daily.temperature_2m_min[0];
        const result: WeatherResult = {
          temp: Math.round((tMax + tMin) / 2),
          temp_max: Math.round(tMax),
          temp_min: Math.round(tMin),
          main: WMO_MAP[code!] || estimateCondition((tMax + tMin) / 2, daily.precipitation_sum?.[0] || 0),
          description: descriptions[code!] || '',
          type: 'forecast',
        };
        setCache(ck, result, TTL_CLIMATE_MS);
        return result;
      }
      return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' };
    }

    // Climate / archive fallback (far-future dates)
    if (diffDays > -1) {
      const month = targetDate.getMonth() + 1;
      const day = targetDate.getDate();
      let refYear = targetDate.getFullYear() - 1;
      // Archive API only has data up to yesterday — go back further if needed
      const yesterday = new Date(now.getTime() - 86400000);
      if (new Date(refYear, month - 1, day + 2) > yesterday) refYear--;
      const startDate = new Date(refYear, month - 1, day - 2);
      const endDate = new Date(refYear, month - 1, day + 2);
      const startStr = startDate.toISOString().slice(0, 10);
      const endStr = endDate.toISOString().slice(0, 10);

      const url = `https://archive-api.open-meteo.com/v1/archive?latitude=${lat}&longitude=${lng}&start_date=${startStr}&end_date=${endStr}&daily=temperature_2m_max,temperature_2m_min,precipitation_sum&timezone=auto`;
      const { response, data } = await fetchOpenMeteo(url);

      if (!response.ok || data.error) {
        throw new ApiError(response.status || 500, data.reason || 'Open-Meteo Climate API error');
      }

      const daily = data.daily;
      if (!daily || !daily.time || daily.time.length === 0) {
        return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' };
      }

      let sumMax = 0,
        sumMin = 0,
        sumPrecip = 0,
        count = 0;
      for (let i = 0; i < daily.time.length; i++) {
        if (daily.temperature_2m_max[i] != null && daily.temperature_2m_min[i] != null) {
          sumMax += daily.temperature_2m_max[i];
          sumMin += daily.temperature_2m_min[i];
          sumPrecip += daily.precipitation_sum![i] || 0;
          count++;
        }
      }

      if (count === 0) {
        return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' };
      }

      const avgMax = sumMax / count;
      const avgMin = sumMin / count;
      const avgTemp = (avgMax + avgMin) / 2;
      const avgPrecip = sumPrecip / count;
      const main = estimateCondition(avgTemp, avgPrecip);

      const result: WeatherResult = {
        temp: Math.round(avgTemp),
        temp_max: Math.round(avgMax),
        temp_min: Math.round(avgMin),
        main,
        description: '',
        type: 'climate',
      };

      setCache(ck, result, TTL_CLIMATE_MS);
      return result;
    }

    return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' };
  }

  // No date supplied -> current weather
  const cached = getCached(ck);
  if (cached) return cached;

  const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}&current=temperature_2m,weathercode&timezone=auto`;
  const { response, data } = await fetchOpenMeteo(url);

  if (!response.ok || data.error) {
    throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error');
  }

  const code = data.current!.weathercode;
  const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN;

  const result: WeatherResult = {
    temp: Math.round(data.current!.temperature_2m),
    main: WMO_MAP[code] || 'Clouds',
    description: descriptions[code] || '',
    type: 'current',
  };

  setCache(ck, result, TTL_CURRENT_MS);
  return result;
}

export async function getWeather(
  rawLat: string,
  rawLng: string,
  date: string | undefined,
  lang: string,
  /** HH:MM of the moment being asked about. Only the archive path can use it. */
  time?: string,
): Promise<WeatherResult> {
  const lat = String(coord(rawLat, 90, 'latitude'));
  const lng = String(coord(rawLng, 180, 'longitude'));
  const ck = cacheKey(lat, lng, date ? `${date}T${time ?? ''}` : date, lang);
  const cached = getCached(ck);
  if (cached) return cached;

  // lang is already part of ck, so the cache key doubles as the in-flight key.
  const existing = inFlight.get(ck);
  if (existing !== undefined) return existing;
  const promise = _getWeatherImpl(lat, lng, date, lang, time);
  inFlight.set(ck, promise);
  try {
    return await promise;
  } finally {
    inFlight.delete(ck);
  }
}

// ── getDetailedWeather ──────────────────────────────────────────────────

/**
 * One day in full (daily figures, sunrise, sunset and the hourly series) from
 * the archive. Null when the archive has no figures for the day yet.
 */
async function detailedFromArchive(
  lat: string,
  lng: string,
  day: string,
  type: 'climate' | 'forecast',
  descriptions: Record<number, string>,
): Promise<WeatherResult | null> {
  const url =
    `https://archive-api.open-meteo.com/v1/archive?latitude=${lat}&longitude=${lng}` +
    `&start_date=${day}&end_date=${day}` +
    `&hourly=temperature_2m,precipitation,weathercode,windspeed_10m,relativehumidity_2m` +
    `&daily=temperature_2m_max,temperature_2m_min,weathercode,precipitation_sum,windspeed_10m_max,sunrise,sunset` +
    `&timezone=auto`;
  const { response, data } = await fetchOpenMeteo(url);

  if (!response.ok || data.error) {
    throw new ApiError(response.status || 500, data.reason || 'Open-Meteo Archive API error');
  }

  const daily = data.daily;
  const hourly = data.hourly;
  if (!daily || !daily.time || daily.time.length === 0 || daily.temperature_2m_max[0] == null) return null;

  const idx = 0;
  const code = daily.weathercode?.[idx];
  const avgMax = daily.temperature_2m_max[idx];
  const avgMin = daily.temperature_2m_min[idx];

  const hourlyData: HourlyEntry[] = [];
  if (hourly?.time) {
    for (let i = 0; i < hourly.time.length; i++) {
      if (hourly.temperature_2m[i] == null) continue;
      const hour = new Date(hourly.time[i]).getHours();
      const hCode = hourly.weathercode?.[i];
      hourlyData.push({
        hour,
        temp: Math.round(hourly.temperature_2m[i]),
        precipitation: hourly.precipitation?.[i] || 0,
        precipitation_probability: 0,
        main: WMO_MAP[hCode!] || 'Clouds',
        wind: Math.round(hourly.windspeed_10m?.[i] || 0),
        humidity: hourly.relativehumidity_2m?.[i] || 0,
      });
    }
  }

  let sunrise: string | null = null,
    sunset: string | null = null;
  if (daily.sunrise?.[idx]) sunrise = daily.sunrise[idx].split('T')[1]?.slice(0, 5);
  if (daily.sunset?.[idx]) sunset = daily.sunset[idx].split('T')[1]?.slice(0, 5);

  return {
    type,
    temp: Math.round((avgMax + avgMin) / 2),
    temp_max: Math.round(avgMax),
    temp_min: Math.round(avgMin),
    main: WMO_MAP[code!] || estimateCondition((avgMax + avgMin) / 2, daily.precipitation_sum?.[idx] || 0),
    description: descriptions[code!] || '',
    precipitation_sum: Math.round((daily.precipitation_sum?.[idx] || 0) * 10) / 10,
    wind_max: Math.round(daily.windspeed_10m_max?.[idx] || 0),
    sunrise,
    sunset,
    hourly: hourlyData,
  };
}

/**
 * The last day Open-Meteo's forecast answers, counted in calendar days from today.
 * The fraction of a day between now and the target's midnight is not that count:
 * the day 16 out lies 15.x days away and slipped through a `<= 16` test (#3216).
 */
const FORECAST_LAST_DAY = 15;

function calendarDaysAhead(day: string, now: Date): number {
  const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
  return Math.round((Date.parse(`${day}T00:00:00Z`) - today) / 86_400_000);
}

/**
 * The forecast counts its range from the place's own date, which trails UTC's in
 * the Americas for part of the day, so its last day can still be refused there,
 * and runs ahead of it east of UTC, where it still answers the day after.
 */
function isOutsideForecastRange(status: number, reason: string | undefined): boolean {
  return status === 400 && /out of allowed range/i.test(reason ?? '');
}

/**
 * Last year's day standing in for a trip day the forecast does not reach. A day
 * at the forecast's edge comes within its reach in hours, so it keeps the
 * forecast's TTL.
 */
async function detailedClimate(
  lat: string,
  lng: string,
  targetDate: Date,
  now: Date,
  descriptions: Record<number, string>,
  ck: string,
  ttlMs: number,
): Promise<WeatherResult> {
  let refYear = targetDate.getFullYear() - 1;
  // Archive API only has data up to yesterday — go back further if needed
  const yesterday = new Date(now.getTime() - 86400000);
  if (new Date(refYear, targetDate.getMonth(), targetDate.getDate()) > yesterday) refYear--;
  const refDateStr = `${refYear}-${String(targetDate.getMonth() + 1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}`;

  const climate = await detailedFromArchive(lat, lng, refDateStr, 'climate', descriptions);
  if (!climate) return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' };
  setCache(ck, climate, ttlMs);
  return climate;
}

async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, lang: string): Promise<WeatherResult> {
  const ck = `detailed_${cacheKey(lat, lng, date, lang)}`;

  const cached = getCached(ck);
  if (cached) return cached;

  const targetDate = new Date(date);
  const now = new Date();
  const diffDays = (targetDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24);
  const dateStr = targetDate.toISOString().slice(0, 10);
  const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN;

  // Climate path: past the last day the forecast answers anywhere, last year's day stands in for the trip's.
  if (calendarDaysAhead(dateStr, now) > FORECAST_LAST_DAY + 1) {
    return detailedClimate(lat, lng, targetDate, now, descriptions, ck, TTL_CLIMATE_MS);
  }

  // Past day: the forecast API answers nulls once a date is a couple of months
  // back, which the day details then showed as 0°. The archive has the real
  // day. It lags a few days behind, so a recent day it cannot answer yet goes
  // on to the forecast API below, which still carries it.
  if (diffDays < -1) {
    const past = await detailedFromArchive(lat, lng, dateStr, 'forecast', descriptions);
    if (past) {
      setCache(ck, past, TTL_CLIMATE_MS);
      return past;
    }
  }

  // Forecast path (up to today + 15 days)
  const url =
    `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}` +
    `&hourly=temperature_2m,precipitation_probability,precipitation,weathercode,windspeed_10m,relativehumidity_2m` +
    `&daily=temperature_2m_max,temperature_2m_min,weathercode,sunrise,sunset,precipitation_probability_max,precipitation_sum,windspeed_10m_max` +
    `&timezone=auto&start_date=${dateStr}&end_date=${dateStr}`;

  const { response, data } = await fetchOpenMeteo(url);

  if (!response.ok || data.error) {
    if (isOutsideForecastRange(response.status, data.reason)) {
      return detailedClimate(lat, lng, targetDate, now, descriptions, ck, TTL_FORECAST_MS);
    }
    throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error');
  }

  const daily = data.daily;
  const hourly = data.hourly;

  // A day outside the model's range comes back as nulls, not as an error.
  if (!daily || !daily.time || daily.time.length === 0 || daily.temperature_2m_max[0] == null) {
    return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' };
  }

  const dayIdx = 0;
  const code = daily.weathercode[dayIdx];

  const formatTime = (isoStr: string) => {
    if (!isoStr) return '';
    const d = new Date(isoStr);
    return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
  };

  const hourlyData: HourlyEntry[] = [];
  if (hourly && hourly.time) {
    for (let i = 0; i < hourly.time.length; i++) {
      const h = new Date(hourly.time[i]).getHours();
      hourlyData.push({
        hour: h,
        temp: Math.round(hourly.temperature_2m[i]),
        precipitation_probability: hourly.precipitation_probability![i] || 0,
        precipitation: hourly.precipitation![i] || 0,
        main: WMO_MAP[hourly.weathercode![i]] || 'Clouds',
        wind: Math.round(hourly.windspeed_10m![i] || 0),
        humidity: Math.round(hourly.relativehumidity_2m![i] || 0),
      });
    }
  }

  const result: WeatherResult = {
    type: 'forecast',
    temp: Math.round((daily.temperature_2m_max[dayIdx] + daily.temperature_2m_min[dayIdx]) / 2),
    temp_max: Math.round(daily.temperature_2m_max[dayIdx]),
    temp_min: Math.round(daily.temperature_2m_min[dayIdx]),
    main: WMO_MAP[code] || 'Clouds',
    description: descriptions[code] || '',
    sunrise: formatTime(daily.sunrise![dayIdx]),
    sunset: formatTime(daily.sunset![dayIdx]),
    precipitation_sum: daily.precipitation_sum![dayIdx] || 0,
    precipitation_probability_max: daily.precipitation_probability_max![dayIdx] || 0,
    wind_max: Math.round(daily.windspeed_10m_max![dayIdx] || 0),
    hourly: hourlyData,
  };

  setCache(ck, result, TTL_FORECAST_MS);
  return result;
}

export async function getDetailedWeather(
  rawLat: string,
  rawLng: string,
  date: string,
  lang: string,
): Promise<WeatherResult> {
  const lat = String(coord(rawLat, 90, 'latitude'));
  const lng = String(coord(rawLng, 180, 'longitude'));
  const ck = `detailed_${cacheKey(lat, lng, date, lang)}`;
  const cached = getCached(ck);
  if (cached) return cached;

  // lang is already part of ck, so the cache key doubles as the in-flight key.
  const existing = inFlight.get(ck);
  if (existing !== undefined) return existing;
  const promise = _getDetailedWeatherImpl(lat, lng, date, lang);
  inFlight.set(ck, promise);
  try {
    return await promise;
  } finally {
    inFlight.delete(ck);
  }
}

// ── ApiError ────────────────────────────────────────────────────────────

export class ApiError extends Error {
  status: number;
  constructor(status: number, message: string) {
    super(message);
    this.status = status;
  }
}