/* eslint-disable functional/no-throw-statements */
/**
 * Tracks the HTTP port the inspector server is bound to, so internal
 * components (currently the MCP server's loopback fetch) can build
 * `http://127.0.0.1:<port>/...` URLs without env-var coupling.
 *
 * Initialization order:
 *   1. `setCurrentPort(port)` — explicit override (used by tests, or any
 *      code that has direct knowledge of the bound port).
 *   2. `process.env.PORT` — fallback. The CLI (`src/cli.ts`) sets this
 *      before spawning the server process, so in normal operation this
 *      branch is taken and no explicit `setCurrentPort` call is needed.
 *
 * `getCurrentPort()` throws if neither source is available.
 */

let overridePort: number | null = null;

export function setCurrentPort(port: number): void {
  if (!Number.isInteger(port) || port <= 0 || port > 65535) {
    throw new Error(`setCurrentPort: invalid port ${port}`);
  }
  overridePort = port;
}

export function getCurrentPort(): number {
  if (overridePort !== null) return overridePort;
  const envPort = process.env["PORT"];
  if (envPort !== undefined && envPort !== "") {
    const n = Number(envPort);
    if (Number.isInteger(n) && n > 0 && n <= 65535) return n;
  }
  throw new Error(
    "Inspector server port not initialized: PORT env var is unset and setCurrentPort() has not been called",
  );
}

/** Reset for tests. */
export function _resetForTests(): void {
  overridePort = null;
}
