#!/usr/bin/env node
"use strict";

// src/server/radar-entrypoint-entry.ts
var import_node_child_process = require("node:child_process");
var import_node_fs = require("node:fs");
var import_node_path = require("node:path");
var REQUIRED_ENV = [
  "CLAUDE_CREDENTIALS_B64",
  "LS_PAT",
  "LS_ORG_SLUG",
  "LS_PROJECT_SLUG",
  "GH_TOKEN"
];
function fail(message) {
  console.error(message);
  process.exit(1);
}
function requireEnv(name) {
  const v = process.env[name];
  if (!v) fail(`ERROR: ${name} is required but not set`);
  return v;
}
function run(cmd, args, stdio = "inherit") {
  const r = (0, import_node_child_process.spawnSync)(cmd, args, { stdio });
  return r.status ?? 1;
}
function setupClaudeCredentials() {
  const home = process.env.HOME ?? "/home/launchpod";
  const claudeDir = (0, import_node_path.join)(home, ".claude");
  (0, import_node_fs.mkdirSync)(claudeDir, { recursive: true });
  const decoded = Buffer.from(requireEnv("CLAUDE_CREDENTIALS_B64"), "base64").toString("utf8");
  const credsPath = (0, import_node_path.join)(claudeDir, ".credentials.json");
  (0, import_node_fs.writeFileSync)(credsPath, decoded);
  (0, import_node_fs.chmodSync)(credsPath, 384);
  const configPath = (0, import_node_path.join)(home, ".claude.json");
  let cfg = {};
  if ((0, import_node_fs.existsSync)(configPath)) {
    try {
      cfg = JSON.parse((0, import_node_fs.readFileSync)(configPath, "utf8"));
    } catch {
      cfg = {};
    }
  }
  cfg.hasCompletedOnboarding = true;
  cfg.lastOnboardingVersion = cfg.lastOnboardingVersion ?? "2.1.159";
  cfg.numStartups = (cfg.numStartups ?? 0) + 1;
  cfg.installMethod = cfg.installMethod ?? "global";
  (0, import_node_fs.writeFileSync)(configPath, JSON.stringify(cfg, null, 2));
  (0, import_node_fs.chmodSync)(configPath, 384);
}
function setupGitAndGh() {
  const name = process.env.GIT_USER_NAME ?? "Radar Bot";
  const email = process.env.GIT_USER_EMAIL ?? "radar@launchpod.local";
  const status = run("launch-kit", ["setup-git", `--identity=${name} <${email}>`]);
  if (status !== 0) fail(`[entrypoint] launch-kit setup-git failed (status ${status})`);
}
function initWorkspaceIfEmpty() {
  process.chdir("/workspace");
  if ((0, import_node_fs.existsSync)(".git")) {
    console.log("[entrypoint] /workspace already initialized \u2014 skipping init");
    return;
  }
  console.log("[entrypoint] /workspace is empty \u2014 running launch-kit init");
  const status = run("launch-kit", [
    "init",
    `--token=${requireEnv("LS_PAT")}`,
    `--org=${requireEnv("LS_ORG_SLUG")}`,
    `--project=${requireEnv("LS_PROJECT_SLUG")}`,
    `--url=${process.env.LS_SERVER_URL ?? "https://launchsecure-v2.vercel.app"}`,
    `--dir=/workspace`
  ]);
  if (status !== 0) fail(`[entrypoint] launch-kit init failed (status ${status})`);
}
function execLaunchPodRadar() {
  console.log("[entrypoint] starting launch-pod radar");
  const child = (0, import_node_child_process.spawn)("launch-pod", ["radar"], { stdio: "inherit" });
  const forward = (sig) => () => {
    try {
      child.kill(sig);
    } catch {
    }
  };
  process.on("SIGTERM", forward("SIGTERM"));
  process.on("SIGINT", forward("SIGINT"));
  process.on("SIGHUP", forward("SIGHUP"));
  child.on("exit", (code, signal) => {
    if (signal) process.kill(process.pid, signal);
    else process.exit(code ?? 0);
  });
}
function main() {
  for (const k of REQUIRED_ENV) requireEnv(k);
  setupClaudeCredentials();
  setupGitAndGh();
  initWorkspaceIfEmpty();
  execLaunchPodRadar();
}
main();
