/**
 * auto-updater.cjs — Version checker for the Electron desktop app.
 *
 * Fetches version.json from the deployed site and compares it to the local
 * version.json. Only checks once per 24 hours unless force=true.
 */

const { readFile } = require('fs/promises');
const { join } = require('path');

const AGENT_ROOT = join(__dirname, '..');
const VERSION_PATH = join(AGENT_ROOT, 'version.json');
const DEFAULT_SITE_URL = 'https://ai-do-site.pages.dev';
const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours

function parseVersion(v) {
  return (String(v || '0.0.0')).split('.').map(n => parseInt(n, 10) || 0);
}

function isNewer(remote, local) {
  const r = parseVersion(remote);
  const l = parseVersion(local);
  for (let i = 0; i < Math.max(r.length, l.length); i++) {
    const rv = r[i] || 0;
    const lv = l[i] || 0;
    if (rv > lv) return true;
    if (rv < lv) return false;
  }
  return false;
}

/**
 * Check for a newer version on the deployed site.
 *
 * @param {object} config  - Agent config object (reads config.siteUrl, config.lastUpdateCheck)
 * @param {boolean} force  - Skip the 24-hour throttle
 * @returns {Promise<{available: boolean, version?: string, changelog?: string, localVersion?: string, lastUpdateCheck?: number}>}
 */
async function checkForUpdates(config = {}, force = false) {
  const siteUrl = (config.siteUrl || DEFAULT_SITE_URL).replace(/\/$/, '');

  // Throttle: only check once per 24 hours unless forced
  if (!force) {
    const lastCheck = config.lastUpdateCheck || 0;
    if (Date.now() - lastCheck < CHECK_INTERVAL_MS) {
      return { available: false, skipped: true };
    }
  }

  // Read local version
  let localVersion = '0.0.0';
  try {
    const raw = await readFile(VERSION_PATH, 'utf-8');
    localVersion = JSON.parse(raw).version || '0.0.0';
  } catch {}

  try {
    const res = await fetch(`${siteUrl}/version.json`, {
      signal: AbortSignal.timeout(8000)
    });
    if (!res.ok) {
      console.warn(`[auto-updater] Remote version fetch failed: HTTP ${res.status}`);
      return { available: false };
    }

    const remote = await res.json();
    const available = isNewer(remote.version, localVersion);

    console.log(`[auto-updater] local=${localVersion} remote=${remote.version} available=${available}`);

    return {
      available,
      version: remote.version,
      changelog: remote.changelog || '',
      localVersion,
      lastUpdateCheck: Date.now()
    };
  } catch (err) {
    console.warn(`[auto-updater] Update check failed: ${err.message}`);
    return { available: false, error: err.message };
  }
}

module.exports = { checkForUpdates };
