import { execFileSync } from "node:child_process";
import { readlinkSync, statSync } from "node:fs";
import { isAbsolute, join, resolve } from "node:path";
import { NODE_LAUNCH_PROOF_PREFIX } from "../cli/launcher-context";
import { parseStopApproval } from "../cli/stop-approval";
import { tokenizeCommandLine } from "../codex/app-server-processes";
import { readProcessCommandLine, type ClientStopOwner } from "../config/process-state";
import { readBoundedRegularFileSync } from "../lib/bounded-file-read";
import { resolveTrustedWindowsPowerShellExe } from "../lib/windows-elevation";
import { windowsProcessNative, windowsProcessPlatform, windowsProcessPlatformSimulated } from "../service/windows-process-native";
import { readDarwinStopArgv, readDarwinStopCwd, readDarwinStopEnvironment, readDarwinStopStart } from "./stop-darwin-process";

const basename = (value: string) => value.toLowerCase().replace(/\\/g, "/").split("/").pop() ?? "";

/** Recognize the invocation that sets the native Child's explicit-stop fence, not any ocx. */
export function isClientStopCommandLine(commandLine: string): boolean {
  if (commandLine.length > 64 * 1024) return false;
  return isClientStopArgv(tokenizeCommandLine(commandLine));
}

export function isClientStopArgv(argv: readonly string[]): boolean {
  const command = ocxCommandIndex(argv);
  return command !== undefined && argv[command] === "stop" && parseStopApproval(argv.slice(command + 1)).ok;
}

export function isLegacyWindowsStartCommandLine(commandLine: string): boolean {
  if (commandLine.length > 64 * 1024) return false;
  const argv = tokenizeCommandLine(commandLine);
  const command = ocxCommandIndex(argv);
  return command !== undefined && argv[command] === "start";
}

function ocxCommandIndex(argv: readonly string[]): number | undefined {
  let next = 1;
  if (/^bun(?:\.exe)?$/.test(basename(argv[0] ?? ""))) {
    if (argv[next] === "run") next++;
    const script = argv[next++]?.replace(/\\/g, "/");
    if (!script || !/(?:^|\/)src\/cli(?:\/index)?\.ts$/i.test(script)) return;
  } else if (!/^(?:ocx|opencodex)(?:\.exe)?$/.test(basename(argv[0] ?? ""))) return;
  // npm inserts this one token before the command. Its spelling is not proof of
  // launcher trust; the current runtime fence and same-user live owner are separate.
  if (argv[next]?.startsWith(NODE_LAUNCH_PROOF_PREFIX)) {
    if (!/^[A-Za-z0-9_-]{43}$/.test(argv[next]!.slice(NODE_LAUNCH_PROOF_PREFIX.length))) return;
    next++;
  }
  return next;
}

/** Creation identity and same-user ownership, sampled freshly for each destructive boundary. */
export function readClientStopProcessStart(pid: number): string | undefined {
  if (!Number.isInteger(pid) || pid <= 0 || pid > 0x7fffffff) return;
  try {
    const platform = windowsProcessPlatform();
    if (platform === "darwin") return readDarwinStopStart(pid);
    if (platform === "linux") {
      const dir = `/proc/${pid}`;
      if (statSync(dir).uid !== process.geteuid?.()) return;
      const stat = readBoundedRegularFileSync(`${dir}/stat`, 4096).toString();
      const end = stat.lastIndexOf(") ");
      const ticks = end < 0 ? undefined : stat.slice(end + 2).trim().split(/\s+/)[19];
      const boot = readBoundedRegularFileSync("/proc/sys/kernel/random/boot_id", 64).toString().trim();
      if (ticks && /^\d+$/.test(ticks) && /^[a-f0-9-]{36}$/.test(boot)) return `linux:${boot}:${ticks}`;
    }
    if (platform === "win32") {
      const native = windowsProcessNative();
      if (native) {
        const identity = native.sameUserIdentity(pid);
        return identity ? `win32:${identity.ticks}` : undefined;
      }
      if (windowsProcessPlatformSimulated()) return;
      // The fallback also binds the SID to this incarnation by refreshing CreationDate.
      const script = `$ErrorActionPreference='Stop'; $p=Get-CimInstance Win32_Process -Filter "ProcessId=${pid}"; $owner=Invoke-CimMethod -InputObject $p -MethodName GetOwnerSid; if ($owner.ReturnValue -eq 0 -and $owner.Sid -eq [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value -and $p.CreationDate) { $after=Get-CimInstance -InputObject $p; if ($after.CreationDate -eq $p.CreationDate) { $p.CreationDate.ToUniversalTime().Ticks } }`;
      const ticks = execFileSync(resolveTrustedWindowsPowerShellExe(), ["-NoProfile", "-NoLogo", "-NonInteractive", "-Command", script], {
        encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 3000, maxBuffer: 1024, windowsHide: true,
      }).trim();
      if (/^\d{1,20}$/.test(ticks)) return `win32:${ticks}`;
    }
  } catch { /* unreadable ownership cannot authorize a native restoration handoff */ }
}

/** Read only the home settings needed to bind a legacy record to its invoking process. */
export function readLegacyStopProcessHome(pid: number): string | undefined {
  try {
    const environment = process.platform === "linux" ? readBoundedRegularFileSync(`/proc/${pid}/environ`, 1024 * 1024)
      : process.platform === "darwin" ? readDarwinStopEnvironment(pid) : undefined;
    if (!environment?.length || environment[environment.length - 1] !== 0) return;
    const setting = (name: string) => {
      const prefix = Buffer.from(`${name}=`);
      for (let offset = 0; offset < environment.length;) {
        const end = environment.indexOf(0, offset);
        if (end < 0) break;
        if (offset + prefix.length <= end && environment.subarray(offset, offset + prefix.length).equals(prefix)) {
          return new TextDecoder("utf-8", { fatal: true }).decode(environment.subarray(offset + prefix.length, end)).trim();
        }
        offset = end + 1;
      }
    };
    const override = setting("OPENCODEX_HOME");
    if (override && isAbsolute(override)) return resolve(override);
    if (override && override !== "~" && !override.startsWith("~/") && !override.startsWith("~\\")) {
      const cwd = process.platform === "linux"
        ? new TextDecoder("utf-8", { fatal: true }).decode(readlinkSync(`/proc/${pid}/cwd`, { encoding: "buffer" }))
        : readDarwinStopCwd(pid);
      // procfs appends this marker when the working directory has been removed.
      if (cwd && isAbsolute(cwd) && !(process.platform === "linux" && cwd.endsWith(" (deleted)"))) return resolve(cwd, override);
      return;
    }
    const home = setting("HOME");
    if (!home || !isAbsolute(home)) return;
    if (!override) return join(home, ".opencodex");
    return override === "~" ? resolve(home) : join(home, override.slice(2));
  } catch { /* An unreadable home cannot bind a legacy record. */ }
}

export type ClientStopOwnerStatus = "active" | "confirmed-stale" | "unverified";

const creationIdentity: Partial<Record<NodeJS.Platform, RegExp>> = {
  darwin: /^darwin:([1-9]\d{0,19}):(?:0|[1-9]\d{0,5})$/,
  linux: /^linux:[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}:(0|[1-9]\d{0,19})$/,
  win32: /^win32:([1-9]\d{0,18})$/,
};

function validCreationIdentity(value: unknown): boolean {
  if (typeof value !== "string" || value.length > 80) return false;
  const platform = windowsProcessPlatform();
  const ticks = creationIdentity[platform]?.exec(value)?.[1];
  return ticks !== undefined && BigInt(ticks) <= (platform === "win32" ? 3155378975999999999n : 0xffffffffffffffffn);
}

/** Bind argv to the creation identity so a recycled PID cannot inherit the fence. */
export function observeClientStopOwner({ pid, startTime, nonce }: ClientStopOwner): ClientStopOwnerStatus {
  if (!Number.isInteger(pid) || pid <= 0 || pid > 0x7fffffff
    || !validCreationIdentity(startTime)
    || typeof nonce !== "string" || !/^[a-f0-9]{32}$/.test(nonce)) return "unverified";
  try { process.kill(pid, 0); }
  catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH" ? "confirmed-stale" : "unverified"; }
  const native = windowsProcessPlatform() === "win32" ? windowsProcessNative() : null;
  if (native) {
    try {
      const identity = native.sameUserIdentity(pid, true);
      if (!identity) return "unverified";
      if (`win32:${identity.ticks}` !== startTime) return "confirmed-stale";
      return pid !== process.pid && identity.commandLine && isClientStopCommandLine(identity.commandLine) ? "active" : "unverified";
    } catch { return "unverified"; }
  }
  // Without a process handle for argv, bracket the read with verified creation identities.
  const before = readClientStopProcessStart(pid);
  if (before === undefined) return "unverified";
  if (before !== startTime) return "confirmed-stale";
  if (pid === process.pid) return "unverified";
  try {
    let stop: boolean;
    if (process.platform === "linux") {
      // /proc exposes argv, not a quoted command line. Preserve NUL boundaries:
      // install paths and approval values can legitimately contain spaces.
      const raw = new TextDecoder("utf8", { fatal: true }).decode(readBoundedRegularFileSync(`/proc/${pid}/cmdline`, 64 * 1024));
      if (raw.length <= 1 || !raw.endsWith("\0")) return "unverified";
      stop = isClientStopArgv(raw.slice(0, -1).split("\0"));
    } else if (process.platform === "darwin") {
      const argv = readDarwinStopArgv(pid);
      if (!argv?.length) return "unverified";
      stop = isClientStopArgv(argv);
    } else {
      const commandLine = readProcessCommandLine(pid);
      if (!commandLine?.trim() || commandLine.length > 64 * 1024) return "unverified";
      stop = isClientStopCommandLine(commandLine);
    }
    const after = readClientStopProcessStart(pid);
    if (after === undefined) return "unverified";
    if (after !== startTime) return "confirmed-stale";
    return stop ? "active" : "unverified";
  } catch { return "unverified"; }
}
