#!/usr/bin/env node
/**
 * postinstall.mjs
 * Automatically sets up arouter server to start on system login/boot.
 * Runs after: npm install -g @thangnm.nip/arouter
 * 
 * Note: MITM server is NOT auto-started. Use the dashboard UI to start it manually.
 */

import fs from 'fs';
import path from 'path';
import os from 'os';
import { execSync } from 'child_process';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Paths
const packageRoot = path.join(__dirname, '..');
const arouterBin = path.join(packageRoot, 'bin', 'arouter.mjs');

const nodeBin = process.execPath;
const platform = os.platform();

function log(msg) {
  console.log(`\x1b[36m[arouter-setup]\x1b[0m ${msg}`);
}

function warn(msg) {
  console.warn(`\x1b[33m[arouter-setup] ⚠️  ${msg}\x1b[0m`);
}

function runCmd(cmd, options = {}) {
  try {
    execSync(cmd, { stdio: 'ignore', ...options });
    return true;
  } catch (e) {
    return false;
  }
}

// ─── macOS Setup ─────────────────────────────────────────────────────────────

function setupMacOS() {
  log('Configuring macOS LaunchAgent for arouter...');

  const launchAgentsDir = path.join(os.homedir(), 'Library', 'LaunchAgents');
  const arouterPlistPath = path.join(launchAgentsDir, 'com.arouter.plist');
  const logDir = path.join(os.homedir(), '.arouter');

  fs.mkdirSync(launchAgentsDir, { recursive: true });
  fs.mkdirSync(logDir, { recursive: true });

  const nodeDir = path.dirname(nodeBin);
  const arouterPlist = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.arouter</string>
    <key>ProgramArguments</key>
    <array>
        <string>${nodeBin}</string>
        <string>${arouterBin}</string>
        <string>start</string>
    </array>
    <key>EnvironmentVariables</key>
    <dict>
        <key>HOME</key>
        <string>${os.homedir()}</string>
        <key>PATH</key>
        <string>${nodeDir}:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
        <key>NODE_ENV</key>
        <string>production</string>
    </dict>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <false/>
    <key>StandardOutPath</key>
    <string>${path.join(logDir, 'startup.log')}</string>
    <key>StandardErrorPath</key>
    <string>${path.join(logDir, 'startup.error.log')}</string>
</dict>
</plist>`;

  fs.writeFileSync(arouterPlistPath, arouterPlist, 'utf8');
  runCmd(`launchctl unload ${arouterPlistPath}`);
  runCmd(`launchctl load ${arouterPlistPath}`);
  log(`✅ Arouter service started`);

  // Clean up old MITM LaunchDaemon if it exists
  const mitmSystemPath = '/Library/LaunchDaemons/com.arouter.mitm.plist';
  if (fs.existsSync(mitmSystemPath)) {
    log('Cleaning up old MITM LaunchDaemon...');
    runCmd(`launchctl unload '${mitmSystemPath}' 2>/dev/null || true`);
  }
}

// ─── Linux Setup ─────────────────────────────────────────────────────────────

function setupLinux() {
  log('Configuring Linux systemd user service for arouter...');

  const logDir = path.join(os.homedir(), '.arouter');
  fs.mkdirSync(logDir, { recursive: true });

  const systemdUserDir = path.join(os.homedir(), '.config', 'systemd', 'user');
  const arouterSvcPath = path.join(systemdUserDir, 'arouter.service');
  fs.mkdirSync(systemdUserDir, { recursive: true });

  const arouterSvc = `[Unit]
Description=arouter - UI Server
After=network.target

[Service]
Type=forking
ExecStart=${nodeBin} ${arouterBin} start
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target
`;
  fs.writeFileSync(arouterSvcPath, arouterSvc, 'utf8');
  runCmd('systemctl --user daemon-reload');
  runCmd('systemctl --user enable arouter');
  runCmd('systemctl --user restart arouter');
  log(`✅ Arouter service started`);

  // Clean up old MITM systemd service if it exists
  const mitmSystemPath = '/etc/systemd/system/arouter-mitm.service';
  if (fs.existsSync(mitmSystemPath)) {
    log('Old MITM systemd service found. You may remove it manually with: sudo systemctl disable arouter-mitm && sudo rm /etc/systemd/system/arouter-mitm.service');
  }
}

// ─── Windows Setup ───────────────────────────────────────────────────────────

function setupWindows() {
  log('Configuring Windows Task Scheduler for arouter...');

  const logDir = path.join(os.homedir(), '.arouter');
  fs.mkdirSync(logDir, { recursive: true });

  const arouterTask = 'arouter';
  const arouterXmlPath = path.join(os.tmpdir(), 'arouter-task.xml');

  const arouterXml = `<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <Triggers><LogonTrigger><Enabled>true</Enabled></LogonTrigger></Triggers>
  <Actions Context="Author"><Exec><Command>${nodeBin}</Command><Arguments>"${arouterBin}" start</Arguments></Exec></Actions>
  <Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><Priority>7</Priority></Settings>
</Task>`;
  fs.writeFileSync(arouterXmlPath, arouterXml, 'utf16le');
  
  if (runCmd(`schtasks /Create /TN "${arouterTask}" /XML "${arouterXmlPath}" /F`)) {
    log(`✅ Arouter scheduled task created`);
  } else {
    warn('Failed to create scheduled task.');
  }

  // Clean up old MITM task if it exists
  runCmd(`schtasks /Delete /TN "arouter-mitm" /F 2>nul`);
}

// ─── Main ────────────────────────────────────────────────────────────────────

function main() {
  // Only run during global install, unless testing locally
  const isGlobal = process.env.npm_config_global === 'true';
  const force = process.argv.includes('--force');

  if (!isGlobal && !force) {
    log('Skipping auto-startup setup (not running as a global install).');
    return;
  }

  log('Setting up auto-startup for arouter server only (MITM not auto-started)...');

  try {
    if (platform === 'darwin') {
      setupMacOS();
    } else if (platform === 'linux') {
      setupLinux();
    } else if (platform === 'win32') {
      setupWindows();
    } else {
      warn(`Platform "${platform}" not supported for auto-startup.`);
    }
    
    log('🎉 Auto-startup configuration finished! (arouter only, MITM must be started from dashboard)');
  } catch (err) {
    warn(`Auto-startup setup failed: ${err.message}`);
  }
}

main();
