/**
 * macOS launchd plist writer — PLAN_RELAY_AGENT T17. The service runs as the LOGGED-IN USER, not
 * root (EXPLORE §4d least privilege); no secrets in the plist (key/cert stay in the keystore).
 */
const LABEL = 'com.web-terminal.agent'

export function launchdLabel(): string {
  return LABEL
}

export function launchdPlistPath(homedir: string): string {
  return `${homedir}/Library/LaunchAgents/${LABEL}.plist`
}

/** Build the plist. ExecStart = `<bin> run`; RunAtLoad + KeepAlive (restart on failure). */
export function buildLaunchdPlist(binPath: string): string {
  return [
    '<?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>${LABEL}</string>`,
    '  <key>ProgramArguments</key>',
    '  <array>',
    `    <string>${binPath}</string>`,
    '    <string>run</string>',
    '  </array>',
    '  <key>RunAtLoad</key>',
    '  <true/>',
    '  <key>KeepAlive</key>',
    '  <true/>',
    '</dict>',
    '</plist>',
    '',
  ].join('\n')
}

export function launchdLoadCommand(plistPath: string): { cmd: string; args: readonly string[] } {
  return { cmd: 'launchctl', args: ['load', plistPath] }
}
export function launchdUnloadCommand(plistPath: string): { cmd: string; args: readonly string[] } {
  return { cmd: 'launchctl', args: ['unload', plistPath] }
}
