import { lstatSync, readFileSync } from "node:fs";
import { execFileSync, execSync } from "node:child_process";
import { existsSync, mkdirSync, unlinkSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { getConfigDir } from "../config";
import { BUN_RUNTIME_PATH_ENV, BUN_RUNTIME_SOURCE_ENV, durableBunRuntime, type DurableBunRuntime } from "../lib/bun-runtime";
import { recordOwnedConfigPath } from "../lib/config-ownership";
import { systemdProperty } from "../service-manager-probe";
import { writeServiceApiTokenFile, sh } from "./guards";
import { shellQuote, buildServiceShellCommand, buildServiceLauncherShellCommand, resolvedProxyEnv, pinnedServiceHomeShellAssignments } from "./definition";
import type { ServiceInstallCleanupOps } from "./orchestration";
import { SERVICE_MANAGED_ENV, TASK, cliEntry, filterTransientServicePath, stableLauncherEntry, logPath, serviceStatePath, currentCodexSqliteHomeAbsolute, currentCodexHome, currentOpenCodexHome, serviceStatePaths, writeServiceInstallState } from "./state";
import { writeServiceDefinitionFile } from "./windows-ops";

/** The `--port <n>` baked into the installed systemd user unit. Linux only. */
export function systemdListenPort(deps: { readUnit?: () => string } = {}): number | null {
  try {
    const text = (deps.readUnit ?? (() => readFileSync(unitPath(), "utf8")))();
    const last = [...text.matchAll(/start --port (\d{1,5})(?:\s|"|$)/gm)].at(-1);
    if (!last) return null;
    const n = Number(last[1]);
    return n > 0 && n <= 65535 ? n : null;
  } catch {
    return null;
  }
}

/**
 * Quote one word for a systemd unit setting. systemd unquotes double-quoted words with C-style
 * escapes (systemd.syntax), so backslash, double quote and line breaks are escaped, and it
 * resolves `%` specifiers in every setting used here, so a literal `%` becomes `%%`.
 */
function systemdQuote(value: string): string {
  return `"${value
    .replace(/\\/g, "\\\\")
    .replace(/"/g, "\\\"")
    .replace(/%/g, "%%")
    .replace(/\n/g, "\\n")
    .replace(/\r/g, "\\r")
    .replace(/\t/g, "\\t")}"`;
}

/**
 * Quote one ExecStart= word. On top of {@link systemdQuote}, ExecStart= expands `$NAME` and
 * `${NAME}` from the unit environment before the program runs (systemd.service, "Command
 * lines"), so a literal `$` must be written `$$`. Environment= does not expand variables,
 * which is why this escape stays out of the shared quoting.
 */
function systemdExecQuote(value: string): string {
  return systemdQuote(value).replace(/\$/g, "$$$$");
}

function systemdEnvironmentAssignment(name: string, value: string | undefined): string | null {
  if (!value) return null;
  return `Environment=${systemdQuote(`${name}=${value}`)}`;
}

// ── Linux (systemd user unit) ──
function unitDir(): string {
  return join(homedir(), ".config", "systemd", "user");
}

export function unitPath(): string {
  return join(unitDir(), `${TASK}.service`);
}

/** On Linux, prove that OpenCodex has no recorded service installation or installer unit. */
export function systemdInstallationAbsent(platform: NodeJS.Platform = process.platform): boolean {
  if (platform !== "linux") return false;
  return [unitPath(), ...serviceStatePaths()].every(path => {
    try { lstatSync(path); return false; }
    catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT"; }
  });
}

export function buildUnit(
  proxyEnv: { name: string; value: string }[] = resolvedProxyEnv(),
  deps: { launcher?: string | null; runtime?: DurableBunRuntime } = {},
): string {
  const runtime = deps.runtime ?? durableBunRuntime();
  const { bun, bunRuntimeSource, cli } = cliEntry(runtime);
  // Discovery belongs to installSystemd(), which resolves once and passes the same value to
  // both the unit and install state. Keeping this builder explicit makes tests and diagnostics
  // independent of the host PATH.
  const launcher = deps.launcher ?? null;
  const log = logPath();
  const path = filterTransientServicePath(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", ":", "linux");
  // Resolve each home once: the default Codex home follows filesystem state (a retargeted
  // ~/.codex link), so a second resolution could write two different homes into one unit.
  const codexHomeValue = currentCodexHome();
  const opencodexHomeValue = currentOpenCodexHome();
  const codexHome = systemdEnvironmentAssignment("CODEX_HOME", codexHomeValue);
  const codexSqliteHome = systemdEnvironmentAssignment("CODEX_SQLITE_HOME", currentCodexSqliteHomeAbsolute());
  const opencodexHome = systemdEnvironmentAssignment("OPENCODEX_HOME", opencodexHomeValue);
  // The Environment= lines are a first pin only: ExecStart is /bin/sh -lc, so a login profile
  // can re-export the homes after systemd supplies them. The command re-assigns both after
  // profile initialization and before exec, with the same shell quoting the rest of the line uses.
  const envLines = [
    systemdEnvironmentAssignment("OCX_SERVICE", "1"),
    systemdEnvironmentAssignment(SERVICE_MANAGED_ENV, "1"),
    ...(launcher ? [] : [
      systemdEnvironmentAssignment(BUN_RUNTIME_SOURCE_ENV, bunRuntimeSource),
      systemdEnvironmentAssignment(BUN_RUNTIME_PATH_ENV, bun),
    ]),
    // A launcher normally resolves the current package's bundled Bun after every upgrade.
    // Preserve only a proof-bound shell override; otherwise writing a package-local path here
    // would recreate the version-manager pin that the launcher mode exists to remove.
    launcher && runtime.source === "override"
      ? systemdEnvironmentAssignment(runtime.overrideEnv, runtime.path)
      : null,
    systemdEnvironmentAssignment("PATH", path),
    codexHome,
    codexSqliteHome,
    opencodexHome,
    ...proxyEnv.map(({ name, value }) => systemdEnvironmentAssignment(name, value)),
  ].filter((line): line is string => Boolean(line)).join("\n");
  const command = `${pinnedServiceHomeShellAssignments(codexHomeValue, opencodexHomeValue)} ${launcher ? buildServiceLauncherShellCommand(launcher) : buildServiceShellCommand(bun, cli)} >> ${shellQuote(log)} 2>&1`;
  return `[Unit]
Description=OpenCodex Proxy Server
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=${systemdExecQuote("/bin/sh")} -lc ${systemdExecQuote(command)}
Restart=on-failure
RestartSec=5
${envLines}

[Install]
WantedBy=default.target
`;
}

/** The per-user runtime dir systemd creates (holds the user-bus socket), or null. */
function userRuntimeDir(): string | null {
  const env = { ...process.env };
  if (env.XDG_RUNTIME_DIR && !existsSync(env.XDG_RUNTIME_DIR)) delete env.XDG_RUNTIME_DIR;
  return systemdUserBusEnvironment(env).XDG_RUNTIME_DIR || null;
}

/** Return explicit SSH user-bus discovery without changing the caller's environment. */
export function systemdUserBusEnvironment(environment: NodeJS.ProcessEnv = process.env, deps: {
  uid?: number; exists?: (path: string) => boolean;
} = {}): NodeJS.ProcessEnv {
  const env = { ...environment };
  if (!env.XDG_RUNTIME_DIR) {
    const uid = deps.uid ?? process.getuid?.();
    const candidate = uid === undefined ? null : `/run/user/${uid}`;
    if (candidate && (deps.exists ?? existsSync)(candidate)) env.XDG_RUNTIME_DIR = candidate;
  }
  return env;
}

/**
 * SSH sessions frequently start without `XDG_RUNTIME_DIR`/`DBUS_SESSION_BUS_ADDRESS`, so
 * `systemctl --user` can't find the user bus even when systemd is running. Point `XDG_RUNTIME_DIR`
 * at the per-user runtime dir when it exists so the `--user` probe and install commands reach the
 * bus. No-op when already set or when no runtime dir exists (e.g. genuinely non-systemd hosts).
 */
function ensureUserBusEnv(): void {
  if (process.env.XDG_RUNTIME_DIR) return;
  const env = systemdUserBusEnvironment();
  if (env.XDG_RUNTIME_DIR) process.env.XDG_RUNTIME_DIR = env.XDG_RUNTIME_DIR;
}

export function isSystemd(): boolean {
  try { execSync("systemctl --version", { stdio: "pipe" }); } catch { return false; }
  ensureUserBusEnv();
  // Prefer the user-bus probe; but an SSH session without a user D-Bus fails it even when systemd
  // is present (F9). Fall back to the per-user runtime dir existing — a strong signal the user
  // systemd instance is available — so a first-time `ocx service install` isn't wrongly refused.
  try { execSync("systemctl --user show-environment", { stdio: "pipe" }); return true; } catch { /* no user bus in this session */ }
  return userRuntimeDir() !== null;
}

export function installSystemd(): void {
  ensureUserBusEnv(); // reach the user bus over a bare SSH session (F9)
  const dir = unitDir();
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
  recordOwnedConfigPath(getConfigDir(), serviceStatePath());
  if (!existsSync(getConfigDir())) mkdirSync(getConfigDir(), { recursive: true });
  writeServiceApiTokenFile();
  // Resolve ONCE and reuse: the unit and the install state must agree about what is
  // launched, or the staleness check would validate a path the unit does not run.
  const launcher = stableLauncherEntry();
  writeServiceDefinitionFile(unitPath(), buildUnit(resolvedProxyEnv(), { launcher }), "utf8");
  sh("systemctl --user daemon-reload");
  sh(`systemctl --user enable ${TASK}`);
  sh(`systemctl --user restart ${TASK}`);
  writeServiceInstallState("scheduler", launcher);
}

/**
 * Whether systemd's in-memory unit differs from the file on disk.
 *
 * The systemd analogue of launchd's stale-plist case: writing
 * `~/.config/systemd/user/<unit>` does not change the definition systemd has loaded
 * until `daemon-reload`, so a plain `systemctl start` would run the PREVIOUS
 * ExecStart. `NeedDaemonReload` is a per-unit property emitted as a bare
 * `NeedDaemonReload=yes|no` line; pass the unit name or `show` reports the manager's
 * own property instead, which answers a different question.
 *
 * Fail-open: if the query cannot run (no user bus, unit absent) we must not block a
 * start that would otherwise work.
 */
export function systemdNeedsDaemonReload(deps: { show?: () => string } = {}): boolean {
  try {
    const out = (deps.show ?? (() => sh(`systemctl --user show -p NeedDaemonReload ${TASK}`)))();
    return /NeedDaemonReload\s*=\s*yes/i.test(out);
  } catch {
    return false;
  }
}

export function startSystemd(): void {
  ensureUserBusEnv();
  if (!existsSync(unitPath())) {
    console.error(`opencodex service is not installed: ${unitPath()}`);
    console.error("Run `ocx service install` first to create and enable the systemd user unit.");
    process.exit(1);
  }
  // The unit on disk may be newer than what systemd loaded; starting now would run
  // the previous definition.
  //
  // `start` alone is not enough after a reload: it is a no-op on an already-active
  // unit, so the stale process would keep running the old ExecStart. NeedDaemonReload
  // compares disk against loaded, never loaded against running, so the only way to
  // make the running process match the file is to restart it.
  if (systemdNeedsDaemonReload()) {
    console.log("ℹ️  unit file changed on disk; reloading systemd and restarting the service.");
    sh("systemctl --user daemon-reload");
    sh(`systemctl --user restart ${TASK}`);
    return;
  }
  sh(`systemctl --user start ${TASK}`);
}

export function stopSystemd(): void { try { sh(`systemctl --user stop ${TASK}`); } catch { /* not running */ } }

export function statusSystemd(): string { try { return sh(`systemctl --user status ${TASK}`); } catch { return ""; } }

/** Strict user-unit inactivity proof for guarded desktop takeover. */
export function probeSystemdUnitInactive(deps: { show?: () => string } = {}): "inactive" | "active" | "unknown" {
  try {
    const output = (deps.show ?? (() => execFileSync("systemctl", ["--user", "show", "-p", "ActiveState", "-p", "MainPID", TASK], {
      encoding: "utf8", timeout: 2_000, stdio: ["ignore", "pipe", "pipe"],
    })))();
    const active = systemdProperty(output, "ActiveState")?.toLowerCase();
    const pid = systemdProperty(output, "MainPID");
    if (active === "inactive" && pid === "0") return "inactive";
    if (["active", "activating", "deactivating", "reloading"].includes(active ?? "")
      || (pid !== null && /^\d+$/.test(pid) && Number(pid) > 0)) return "active";
    return "unknown";
  } catch { return "unknown"; }
}

export function uninstallSystemd(deps: {
  run?: (command: string) => string;
  unitExists?: () => boolean;
  removeUnit?: () => void;
} = {}): void {
  const run = deps.run ?? sh;
  try { run(`systemctl --user stop ${TASK}`); } catch { /* not running */ }
  try { run(`systemctl --user disable ${TASK}`); } catch { /* absent */ }
  if ((deps.unitExists ?? (() => existsSync(unitPath())))()) {
    (deps.removeUnit ?? (() => unlinkSync(unitPath())))();
  }
  try { run("systemctl --user daemon-reload"); } catch { /* best-effort */ }
}

export function systemdServiceInstallCleanupOps(deps: {
  run?: (command: string) => string;
} = {}): ServiceInstallCleanupOps {
  const run = deps.run ?? sh;
  return {
    status: () => {
      const output = run(`systemctl --user show -p LoadState ${TASK}`);
      const loadState = systemdProperty(output, "LoadState")?.toLowerCase();
      if (!loadState) throw new Error("systemd service status could not be verified.");
      return loadState === "not-found" ? null : loadState;
    },
    stop: () => { run(`systemctl --user stop ${TASK}`); },
  };
}
