#!/usr/bin/env node
// Windows service registration for the hub-agent.
//
// node-windows installs winsw under the hood, which gives us a real Windows
// service (auto-start at boot, restart on crash, proper stdin/stdout
// handling). We don't bundle node-windows in package.json — the install
// script installs it ad-hoc since it's only needed at install time.
//
// Usage (called by install-windows.ps1):
//   node win-service.js install          # register + start
//   node win-service.js uninstall        # stop + unregister

const path = require('path');
let Service;
try {
  Service = require('node-windows').Service;
} catch (e) {
  console.error('node-windows is not installed. Run from install-windows.ps1, not directly.');
  process.exit(1);
}

const installDir = process.env.APPMINT_HUB_INSTALL_DIR || 'C:\\Program Files\\AppmintHub';
const svc = new Service({
  name: 'AppmintHub',
  description: 'Appmint device hub agent — bridges local USB hardware to the Appmint cloud.',
  script: path.join(installDir, 'dist', 'index.js'),
  workingDirectory: installDir,
  env: [
    { name: 'NODE_ENV', value: 'production' },
    { name: 'APPMINT_HUB_CONFIG', value: process.env.APPMINT_HUB_CONFIG || 'C:\\ProgramData\\AppmintHub\\config.json' },
  ],
  // Restart aggressively on crash; throttle so we don't spin.
  wait: 2,
  grow: 0.5,
  maxRetries: 40,
});

const cmd = process.argv[2];

if (cmd === 'install') {
  svc.on('install', () => {
    console.log('AppmintHub service installed. Starting…');
    svc.start();
  });
  svc.on('start', () => console.log('AppmintHub service started. Logs in Windows Event Viewer.'));
  svc.on('error', (e) => console.error('install failed:', e.message));
  svc.install();
} else if (cmd === 'uninstall') {
  svc.on('uninstall', () => console.log('AppmintHub service removed.'));
  svc.uninstall();
} else {
  console.error('Usage: node win-service.js [install|uninstall]');
  process.exit(1);
}
