/**
 * Cross-platform service installer for ffctk
 *
 * Linux: systemd user unit (~/.config/systemd/user/ffctk.service)
 * macOS: launchd user agent (~/Library/LaunchAgents/com.ff.ffctk.plist)
 * Windows: registers via sc.exe + powershell auto-start hook
 */
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { execSync } from 'child_process';
import { getOsPlatform } from './config';

const SERVICE_NAME = 'ffctk';

export function installService(binPath: string) {
  const platform = getOsPlatform();
  if (platform === 'LINUX') return installLinuxSystemd(binPath);
  if (platform === 'DARWIN') return installMacosLaunchd(binPath);
  if (platform === 'WINDOWS') return installWindows(binPath);
  throw new Error(`Unsupported platform: ${platform}`);
}

export function uninstallService() {
  const platform = getOsPlatform();
  if (platform === 'LINUX') return uninstallLinuxSystemd();
  if (platform === 'DARWIN') return uninstallMacosLaunchd();
  if (platform === 'WINDOWS') return uninstallWindows();
  throw new Error(`Unsupported platform: ${platform}`);
}

// ============ Linux (systemd user) ============

function installLinuxSystemd(binPath: string) {
  const unitDir = path.join(os.homedir(), '.config', 'systemd', 'user');
  fs.mkdirSync(unitDir, { recursive: true });
  const unitPath = path.join(unitDir, `${SERVICE_NAME}.service`);
  const logFile = path.join(os.homedir(), '.cache', 'ffctk', 'ffctk.log');
  const unit = `[Unit]
Description=FF AI Coding Tools Usage Tracker
After=network-online.target

[Service]
Type=simple
ExecStart=${binPath} start
Restart=on-failure
RestartSec=10
StandardOutput=append:${logFile}
StandardError=append:${logFile}

[Install]
WantedBy=default.target
`;
  fs.writeFileSync(unitPath, unit, { mode: 0o644 });
  console.log(`✅ systemd unit written to ${unitPath}`);
  try {
    execSync(`systemctl --user daemon-reload`, { stdio: 'inherit' });
    execSync(`systemctl --user enable ${SERVICE_NAME}.service`, { stdio: 'inherit' });
    execSync(`systemctl --user start ${SERVICE_NAME}.service`, { stdio: 'inherit' });
    console.log(`✅ Service enabled + started. View logs: journalctl --user -u ${SERVICE_NAME} -f`);
    console.log(`💡 To survive logout: sudo loginctl enable-linger $USER`);
  } catch (e: any) {
    console.warn(`systemctl call failed: ${e.message}`);
    console.warn(`Run manually: systemctl --user daemon-reload && systemctl --user enable --now ${SERVICE_NAME}`);
  }
}

function uninstallLinuxSystemd() {
  try {
    execSync(`systemctl --user stop ${SERVICE_NAME}.service`, { stdio: 'inherit' });
    execSync(`systemctl --user disable ${SERVICE_NAME}.service`, { stdio: 'inherit' });
  } catch {}
  const unitPath = path.join(os.homedir(), '.config', 'systemd', 'user', `${SERVICE_NAME}.service`);
  if (fs.existsSync(unitPath)) fs.unlinkSync(unitPath);
  execSync(`systemctl --user daemon-reload`, { stdio: 'inherit' });
  console.log('✅ Uninstalled systemd unit');
}

// ============ macOS (launchd) ============

function installMacosLaunchd(binPath: string) {
  const agentDir = path.join(os.homedir(), 'Library', 'LaunchAgents');
  fs.mkdirSync(agentDir, { recursive: true });
  const plistPath = path.join(agentDir, `com.ff.${SERVICE_NAME}.plist`);
  const logFile = path.join(os.homedir(), '.cache', 'ffctk', 'ffctk.log');
  const plist = `<?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.ff.${SERVICE_NAME}</string>
  <key>ProgramArguments</key>
  <array>
    <string>${binPath}</string>
    <string>start</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>${logFile}</string>
  <key>StandardErrorPath</key>
  <string>${logFile}</string>
</dict>
</plist>
`;
  fs.writeFileSync(plistPath, plist, { mode: 0o644 });
  console.log(`✅ launchd plist written to ${plistPath}`);
  try {
    execSync(`launchctl unload "${plistPath}" 2>/dev/null || true`, { shell: '/bin/bash' } as any);
    execSync(`launchctl load -w "${plistPath}"`, { stdio: 'inherit' });
    console.log(`✅ Agent loaded. View logs: tail -f ${logFile}`);
  } catch (e: any) {
    console.warn(`launchctl call failed: ${e.message}`);
  }
}

function uninstallMacosLaunchd() {
  const plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', `com.ff.${SERVICE_NAME}.plist`);
  try {
    execSync(`launchctl unload "${plistPath}"`, { stdio: 'inherit' });
  } catch {}
  if (fs.existsSync(plistPath)) fs.unlinkSync(plistPath);
  console.log('✅ Uninstalled launchd agent');
}

// ============ Windows (Task Scheduler via schtasks) ============

function installWindows(binPath: string) {
  // 用 schtasks 注册一个开机自启任务，比 sc.exe 服务简单且不需要 wrap nssm
  const taskName = SERVICE_NAME;
  const cmd = `schtasks /Create /SC ONLOGON /TN "${taskName}" /TR "\\"${binPath}\\" start" /RL HIGHEST /F`;
  try {
    execSync(cmd, { stdio: 'inherit', shell: 'cmd.exe' });
    execSync(`schtasks /Run /TN "${taskName}"`, { stdio: 'inherit', shell: 'cmd.exe' });
    console.log(`✅ Scheduled task ${taskName} created (runs on logon)`);
  } catch (e: any) {
    console.warn(`schtasks call failed: ${e.message}`);
    console.warn(`Run manually: ${cmd}`);
  }
}

function uninstallWindows() {
  try {
    execSync(`schtasks /End /TN "${SERVICE_NAME}" 2>nul`, { shell: 'cmd.exe' } as any);
    execSync(`schtasks /Delete /TN "${SERVICE_NAME}" /F`, { stdio: 'inherit', shell: 'cmd.exe' });
    console.log('✅ Scheduled task deleted');
  } catch (e: any) {
    console.warn(`Uninstall failed: ${e.message}`);
  }
}
