const require = (await import('node:module')).createRequire(import.meta.url); const __chunk_filename = (await import('node:url')).fileURLToPath(import.meta.url); const __chunk_dirname = (await import('node:path')).dirname(__chunk_filename);
import {
  exitCli,
  require_source
} from "./chunk-NRSJ3JUA.js";
import {
  DEFAULT_PORT,
  SERVER_START_WAIT_MS,
  getBinaryPath,
  getLiteRtBinDir,
  getLogFilePath,
  getPidFilePath,
  isBinaryInstalled,
  isServerRunning,
  resolveGemmaConfig,
  writeServerProcessInfo
} from "./chunk-P3GSBAEP.js";
import {
  debugLogger
} from "./chunk-3AIAY5PD.js";
import {
  __toESM
} from "./chunk-34MYV7JD.js";

// packages/cli/src/commands/gemma/start.ts
var import_chalk = __toESM(require_source(), 1);
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
async function startServer(binaryPath, port) {
  const alreadyRunning = await isServerRunning(port);
  if (alreadyRunning) {
    debugLogger.log(`LiteRT server already running on port ${port}`);
    return true;
  }
  const logPath = getLogFilePath();
  fs.mkdirSync(getLiteRtBinDir(), { recursive: true });
  const tmpDir = path.dirname(getPidFilePath());
  fs.mkdirSync(tmpDir, { recursive: true });
  const logFd = fs.openSync(logPath, "a");
  try {
    const child = spawn(binaryPath, ["serve", `--port=${port}`, "--verbose"], {
      detached: true,
      stdio: ["ignore", logFd, logFd]
    });
    if (child.pid) {
      writeServerProcessInfo({
        pid: child.pid,
        binaryPath,
        port
      });
    }
    child.unref();
  } finally {
    fs.closeSync(logFd);
  }
  await new Promise((resolve) => setTimeout(resolve, SERVER_START_WAIT_MS));
  return isServerRunning(port);
}
var startCommand = {
  command: "start",
  describe: "Start the LiteRT-LM server",
  builder: (yargs) => yargs.option("port", {
    type: "number",
    description: "Port for the LiteRT server"
  }),
  handler: async (argv) => {
    let port;
    if (argv["port"] !== void 0) {
      port = Number(argv["port"]);
    }
    if (!port) {
      const { configuredPort } = resolveGemmaConfig(DEFAULT_PORT);
      port = configuredPort;
    }
    const binaryPath = getBinaryPath();
    if (!binaryPath || !isBinaryInstalled(binaryPath)) {
      debugLogger.error(
        import_chalk.default.red(
          'LiteRT-LM binary not found. Run "gemini gemma setup" first.'
        )
      );
      await exitCli(1);
      return;
    }
    const alreadyRunning = await isServerRunning(port);
    if (alreadyRunning) {
      debugLogger.log(
        import_chalk.default.green(`LiteRT server is already running on port ${port}.`)
      );
      await exitCli(0);
      return;
    }
    debugLogger.log(`Starting LiteRT server on port ${port}...`);
    const started = await startServer(binaryPath, port);
    if (started) {
      debugLogger.log(import_chalk.default.green(`LiteRT server started on port ${port}.`));
      debugLogger.log(import_chalk.default.dim(`Logs: ${getLogFilePath()}`));
      await exitCli(0);
    } else {
      debugLogger.error(
        import_chalk.default.red("Server may not have started correctly. Check logs:")
      );
      debugLogger.error(import_chalk.default.dim(`  ${getLogFilePath()}`));
      await exitCli(1);
    }
  }
};

export {
  startServer,
  startCommand
};
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
