/**
 * 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).
 *
 * PLAN_NATIVE_TUNNEL S2: the plist can now inject a caller-supplied per-host env map
 * (BIND_HOST, ALLOWED_ORIGINS, PORT, SHELL_PATH, IDLE_TTL, USE_TMUX, …) as a launchd
 * `<key>EnvironmentVariables</key><dict>…</dict>` block. Values are XML-escaped and keys are
 * sorted for deterministic, immutable output.
 */

/** Shared env-map shape for the durable-service writers (launchd + systemd). Immutable. */
export type ServiceEnv = Readonly<Record<string, string>>

const LABEL = 'com.web-terminal.agent'

export function launchdLabel(): string {
  return LABEL
}

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

/** Escape the five XML-significant characters so env keys/values/paths are plist-safe. */
function escapeXml(value: string): string {
  return value
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;')
}

/** Build the `<key>EnvironmentVariables</key><dict>…</dict>` lines (empty array when env is empty). */
function environmentVariablesBlock(env: ServiceEnv): readonly string[] {
  const entries = Object.entries(env).sort(([a], [b]) => a.localeCompare(b))
  if (entries.length === 0) return []
  const lines = ['  <key>EnvironmentVariables</key>', '  <dict>']
  for (const [key, value] of entries) {
    lines.push(`    <key>${escapeXml(key)}</key>`)
    lines.push(`    <string>${escapeXml(value)}</string>`)
  }
  lines.push('  </dict>')
  return lines
}

/**
 * Build the plist. ExecStart = `<bin> run`; RunAtLoad + KeepAlive (restart on failure). When `env`
 * is non-empty, a launchd `EnvironmentVariables` dict is injected so the supervised process
 * receives the per-host tunnel config. Pure/immutable — returns a fresh string.
 */
export function buildLaunchdPlist(binPath: string, env: ServiceEnv = {}): 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>${escapeXml(LABEL)}</string>`,
    '  <key>ProgramArguments</key>',
    '  <array>',
    `    <string>${escapeXml(binPath)}</string>`,
    '    <string>run</string>',
    '  </array>',
    '  <key>RunAtLoad</key>',
    '  <true/>',
    '  <key>KeepAlive</key>',
    '  <true/>',
    ...environmentVariablesBlock(env),
    '</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] }
}
