// api.jsx — client for the TempoLavra Worker (/api/v3, and /api/v4 for the LoRa mesh).
// The dashboard token (the Worker's READ_TOKEN) lives in localStorage and goes
// as "Authorization: Bearer"; photos take it as ?token= because <img> can't send headers.

const TOKEN_KEY = 'tempolavra_token';

function getToken() {
  try { return localStorage.getItem(TOKEN_KEY) || ''; } catch { return ''; }
}

function setToken(t) {
  try {
    if (t) localStorage.setItem(TOKEN_KEY, t);
    else localStorage.removeItem(TOKEN_KEY);
  } catch { /* private mode */ }
}

class AuthError extends Error {}

async function call(path, options = {}) {
  const res = await fetch(path, {
    ...options,
    headers: { Authorization: `Bearer ${getToken()}`, 'Content-Type': 'application/json', ...(options.headers || {}) },
  });
  if (res.status === 401) throw new AuthError('token inválido');
  const json = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
  return json;
}

// Only what the dashboard draws (the full row has more columns)
const DASH_COLUMNS = [
  'ts', 'utc', 'time_src', 'firmware', 'temperature', 'humidity', 'pressure', 'sky_temperature',
  'ambient_temperature', 'cloud_cover', 'thermal_min', 'thermal_median', 'thermal_max', 'thermal_cloud_pct',
  'lux', 'uv_index', 'wind_dir_deg', 'wind_speed_kmh', 'wind_gust_kmh',
  'rain_mm', 'interval_s', 'battery_voltage', 'battery_percent', 'charging', 'input_present',
  'sensors_ok', 'gps_fix', 'latitude', 'longitude', 'altitude_m', 'satellites', 'hdop',
  'rain_probability', 'rain_prediction', 'photo', 'prev_awake_ms', 'prev_wifi_rssi',
  'queue_backlog', 'boot_count', 'received_at',
].join(',');

async function fetchDevices() {
  return (await call('/api/v3/devices')).devices || [];
}

// Rows with ts >= fromTs, oldest first, following the pagination cursor.
async function fetchReadings(deviceId, fromTs) {
  let rows = [];
  let after = 0;
  for (let page = 0; page < 10; page++) {
    const q = new URLSearchParams({
      device_id: deviceId, format: 'json', limit: '5000', after_seq: String(after),
      from: String(fromTs), columns: DASH_COLUMNS,
    });
    const json = await call(`/api/v3/readings?${q}`);
    rows = rows.concat(json.readings || []);
    if (json.next_after_seq == null) break;
    after = json.next_after_seq;
  }
  return rows;
}

async function fetchPhotos(deviceId, fromTs, limit = 2000) {
  const q = new URLSearchParams({ device_id: deviceId, from: String(fromTs), limit: String(limit) });
  return (await call(`/api/v3/photos?${q}`)).photos || [];
}

// MLX90640 sky maps (optional sensor): same list endpoint, kind=thermal
async function fetchThermal(deviceId, fromTs, limit = 2000) {
  const q = new URLSearchParams({ device_id: deviceId, from: String(fromTs), limit: String(limit), kind: 'thermal' });
  return (await call(`/api/v3/photos?${q}`)).photos || [];
}

// One map: { ref, px: Float32Array(768) } in deg C (NaN = no value). File format in
// firmware/components/thermal/include/thermal_stats.h.
const thermalCache = new Map();
async function fetchThermalMap(deviceId, path) {
  const key = `${deviceId}/${path}`;
  if (thermalCache.has(key)) return thermalCache.get(key);
  const res = await fetch(photoUrl(deviceId, path));
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const view = new DataView(await res.arrayBuffer());
  if (view.byteLength !== 1542 || view.getUint32(0, false) !== 0x544c5431) throw new Error('mapa térmico inválido');
  const val = (off) => { const v = view.getInt16(off, true); return v === 0x7fff ? NaN : v / 100; };
  const px = new Float32Array(768);
  for (let i = 0; i < 768; i++) px[i] = val(6 + 2 * i);
  const map = { ref: val(4), px };
  thermalCache.set(key, map);
  return map;
}

function photoUrl(deviceId, path) {
  const q = new URLSearchParams({ device_id: deviceId, path, token: getToken() });
  return `/api/v3/photo?${q}`;
}

function csvUrl(deviceId, fromTs) {
  const q = new URLSearchParams({ device_id: deviceId, token: getToken() });
  if (fromTs) q.set('from', String(fromTs));
  return `/api/v3/readings?${q}`;
}

async function setInterval_(deviceId, minutes) {
  return call('/api/v3/devices/config', {
    method: 'PUT',
    body: JSON.stringify({ device_id: deviceId, measure_interval_minutes: minutes }),
  });
}

async function fetchMesh() {
  return (await call('/api/v4/mesh')).networks || [];
}

async function wifiRequest(deviceId) {
  return call('/api/v4/devices/wifi-request', { method: 'PUT', body: JSON.stringify({ device_id: deviceId }) });
}

/** Sink: release the microSD for `minutes` (0 cancels) so the card can be swapped. */
async function sdEject(deviceId, minutes = 15) {
  return call('/api/v4/devices/sd-eject', { method: 'PUT', body: JSON.stringify({ device_id: deviceId, minutes }) });
}

Object.assign(window, {
  AS_API: {
    getToken, setToken, AuthError, fetchDevices, fetchReadings, fetchPhotos, fetchThermal, fetchThermalMap, photoUrl, csvUrl,
    setInterval: setInterval_, fetchMesh, wifiRequest, sdEject,
  },
});
