// @bun
import {
  init_ListItem
} from "./chunk-8fna3en6.js";
import {
  buildCliLaunch,
  init_cliLaunch,
  spawnCli
} from "./chunk-7w9j5817.js";
import {
  init_Dialog
} from "./chunk-4gjhjt2k.js";
import {
  init_overlayContext,
  useRegisterOverlay
} from "./chunk-e91vvygt.js";
import"./chunk-k60b56gr.js";
import"./chunk-14p6wvsq.js";
import"./chunk-n66h7gtd.js";
import"./chunk-28jd8qjx.js";
import"./chunk-djt39ze3.js";
import"./chunk-9a9g5hbj.js";
import"./chunk-ptxteaeh.js";
import"./chunk-ftrj0crk.js";
import"./chunk-yrpthe2x.js";
import"./chunk-10fpzkhd.js";
import"./chunk-awz3dq2e.js";
import"./chunk-2tabctw9.js";
import"./chunk-z21x0z3h.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-qn6me9n1.js";
import"./chunk-9rwstxn3.js";
import {
  getBridgeDisabledReason,
  init_bridgeEnabled
} from "./chunk-td4ter5p.js";
import {
  BRIDGE_LOGIN_INSTRUCTION,
  init_types
} from "./chunk-71sdcaq6.js";
import"./chunk-cb6yemrf.js";
import"./chunk-tj8te4np.js";
import"./chunk-jjh8y2m7.js";
import"./chunk-dr2x4ze7.js";
import"./chunk-8ad8jmrf.js";
import"./chunk-24kv69g3.js";
import"./chunk-68n1gfc7.js";
import"./chunk-1w7c5hws.js";
import"./chunk-4gyjc4jm.js";
import"./chunk-4spgkgr3.js";
import"./chunk-e8dhxycp.js";
import"./chunk-hf0jvnz1.js";
import {
  init_useKeybinding
} from "./chunk-9pygs2bc.js";
import"./chunk-60fkafk2.js";
import"./chunk-gaazk5m4.js";
import"./chunk-vgmsapsy.js";
import"./chunk-093ej2sf.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-nde5ym6a.js";
import"./chunk-zypcr179.js";
import"./chunk-etcs82b2.js";
import {
  getBridgeAccessToken,
  init_bridgeConfig
} from "./chunk-7wy0nfkf.js";
import"./chunk-1emjj9xz.js";
import"./chunk-m1hz377a.js";
import"./chunk-4nctdw69.js";
import"./chunk-vhghhw4q.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-hdwp8fte.js";
import"./chunk-hqxp6b72.js";
import"./chunk-3cwfww0q.js";
import"./chunk-xqc9bbe3.js";
import"./chunk-w5hnghah.js";
import"./chunk-qm7pdcft.js";
import"./chunk-x59e8cv0.js";
import"./chunk-s76nvx50.js";
import"./chunk-7jyr5758.js";
import"./chunk-zrpa39fh.js";
import"./chunk-nkg1b3qw.js";
import"./chunk-c1kx8bry.js";
import"./chunk-epvbnq43.js";
import"./chunk-swgt1px0.js";
import"./chunk-8kf8h7xf.js";
import"./chunk-swz6krys.js";
import"./chunk-7eywm3ed.js";
import"./chunk-bgan4cpf.js";
import"./chunk-jmv7k0jn.js";
import"./chunk-25w7rxtr.js";
import"./chunk-5xfj4jkd.js";
import"./chunk-c1t99xmt.js";
import"./chunk-vwenx8ke.js";
import"./chunk-8thwr7p8.js";
import"./chunk-v4ypszbb.js";
import"./chunk-bk6ck5c2.js";
import"./chunk-ym6j0wv1.js";
import"./chunk-hjmatcgt.js";
import"./chunk-6mdh70q0.js";
import"./chunk-ch92ycde.js";
import"./chunk-e4dsy4g1.js";
import"./chunk-326zehp8.js";
import"./chunk-kc67kt75.js";
import"./chunk-40t1d75v.js";
import"./chunk-rt34thxn.js";
import"./chunk-e3abfxpy.js";
import"./chunk-q44zc68f.js";
import"./chunk-fejeqe61.js";
import"./chunk-kgkdmr0x.js";
import"./chunk-hn4w9pkj.js";
import {
  Dialog,
  ListItem,
  ThemedBox_default,
  ThemedText,
  init_src,
  require_react,
  useKeybindings
} from "./chunk-cswpvb8x.js";
import {
  require_jsx_runtime
} from "./chunk-gxyx8b8w.js";
import"./chunk-j1mep9ck.js";
import"./chunk-6x35ffpx.js";
import"./chunk-1zbwhcbt.js";
import"./chunk-ddaxg4xh.js";
import"./chunk-vvh31np8.js";
import"./chunk-tywrrc1m.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-4p0hxk2c.js";
import"./chunk-c4dyxsat.js";
import"./chunk-34rn09za.js";
import"./chunk-m28vg9w4.js";
import"./chunk-rk9fgqmg.js";
import"./chunk-nw4zt0y4.js";
import"./chunk-c1yc761e.js";
import"./chunk-c5g9shkw.js";
import {
  errorMessage,
  init_errors
} from "./chunk-k9jzhhww.js";
import"./chunk-kb3758f7.js";
import"./chunk-xqs9r7pg.js";
import"./chunk-tj0dzck2.js";
import"./chunk-aeysytks.js";
import"./chunk-ns1htxgd.js";
import"./chunk-ztqzmfx1.js";
import"./chunk-6k1rsk85.js";
import"./chunk-nxzx0ey9.js";
import"./chunk-yes1my80.js";
import"./chunk-pecy49yr.js";
import"./chunk-azbab59e.js";
import"./chunk-3nk9q8dr.js";
import {
  __esm,
  __toESM
} from "./chunk-hhsxm2yr.js";

// src/commands/remoteControlServer/remoteControlServer.tsx
import { resolve } from "path";
function RemoteControlServer({ onDone }) {
  const [status, setStatus] = import_react.useState(daemonStatus);
  const [error, setError] = import_react.useState(null);
  import_react.useEffect(() => {
    if (daemonProcess && !daemonProcess.killed) {
      setStatus("running");
      return;
    }
    let cancelled = false;
    (async () => {
      const checkError = await checkPrerequisites();
      if (cancelled)
        return;
      if (checkError) {
        onDone(checkError, { display: "system" });
        return;
      }
      setStatus("starting");
      try {
        startDaemon();
        if (!cancelled) {
          setStatus("running");
          daemonStatus = "running";
          onDone("Remote Control Server started. Use /remote-control-server to manage.", { display: "system" });
        }
      } catch (err) {
        if (!cancelled) {
          const msg = errorMessage(err);
          setStatus("error");
          setError(msg);
          daemonStatus = "error";
          onDone(`Remote Control Server failed to start: ${msg}`, {
            display: "system"
          });
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);
  if (status === "running" && daemonProcess && !daemonProcess.killed) {
    return /* @__PURE__ */ jsx_runtime.jsx(ServerManagementDialog, {
      onDone
    });
  }
  if (status === "error" && error) {
    return null;
  }
  return null;
}
function ServerManagementDialog({ onDone }) {
  useRegisterOverlay("remote-control-server-dialog");
  const [focusIndex, setFocusIndex] = import_react.useState(2);
  const logPreview = daemonLogs.slice(-5);
  function handleStop() {
    stopDaemon();
    onDone("Remote Control Server stopped.", { display: "system" });
  }
  function handleRestart() {
    stopDaemon();
    try {
      startDaemon();
      onDone("Remote Control Server restarted.", { display: "system" });
    } catch (err) {
      onDone(`Failed to restart: ${errorMessage(err)}`, { display: "system" });
    }
  }
  function handleContinue() {
    onDone(undefined, { display: "skip" });
  }
  const ITEM_COUNT = 3;
  useKeybindings({
    "select:next": () => setFocusIndex((i) => (i + 1) % ITEM_COUNT),
    "select:previous": () => setFocusIndex((i) => (i - 1 + ITEM_COUNT) % ITEM_COUNT),
    "select:accept": () => {
      if (focusIndex === 0) {
        handleStop();
      } else if (focusIndex === 1) {
        handleRestart();
      } else {
        handleContinue();
      }
    }
  }, { context: "Select" });
  return /* @__PURE__ */ jsx_runtime.jsx(Dialog, {
    title: "Remote Control Server",
    onCancel: handleContinue,
    hideInputGuide: true,
    children: /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
      flexDirection: "column",
      gap: 1,
      children: [
        /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
          children: [
            "Remote Control Server is",
            " ",
            /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
              bold: true,
              color: "success",
              children: "running"
            }),
            daemonProcess ? ` (PID: ${daemonProcess.pid})` : ""
          ]
        }),
        logPreview.length > 0 && /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
          flexDirection: "column",
          children: [
            /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
              dimColor: true,
              children: "Recent logs:"
            }),
            logPreview.map((line, i) => /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
              dimColor: true,
              children: line
            }, i))
          ]
        }),
        /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
          flexDirection: "column",
          children: [
            /* @__PURE__ */ jsx_runtime.jsx(ListItem, {
              isFocused: focusIndex === 0,
              children: /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                children: "Stop server"
              })
            }),
            /* @__PURE__ */ jsx_runtime.jsx(ListItem, {
              isFocused: focusIndex === 1,
              children: /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                children: "Restart server"
              })
            }),
            /* @__PURE__ */ jsx_runtime.jsx(ListItem, {
              isFocused: focusIndex === 2,
              children: /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                children: "Continue"
              })
            })
          ]
        }),
        /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          dimColor: true,
          children: "Enter to select \xB7 Esc to continue"
        })
      ]
    })
  });
}
async function checkPrerequisites() {
  const disabledReason = await getBridgeDisabledReason();
  if (disabledReason) {
    return disabledReason;
  }
  if (!getBridgeAccessToken()) {
    return BRIDGE_LOGIN_INSTRUCTION;
  }
  return null;
}
function startDaemon() {
  const dir = resolve(".");
  const launch = buildCliLaunch(["daemon", "start", `--dir=${dir}`]);
  const child = spawnCli(launch, {
    cwd: dir,
    stdio: ["ignore", "pipe", "pipe"],
    detached: false
  });
  daemonProcess = child;
  daemonLogs = [];
  child.stdout?.on("data", (data) => {
    const lines = data.toString().trimEnd().split(`
`);
    for (const line of lines) {
      daemonLogs.push(line);
      if (daemonLogs.length > MAX_LOG_LINES) {
        daemonLogs.shift();
      }
    }
  });
  child.stderr?.on("data", (data) => {
    const lines = data.toString().trimEnd().split(`
`);
    for (const line of lines) {
      daemonLogs.push(`[err] ${line}`);
      if (daemonLogs.length > MAX_LOG_LINES) {
        daemonLogs.shift();
      }
    }
  });
  child.on("exit", (code, signal) => {
    daemonProcess = null;
    daemonStatus = "stopped";
    daemonLogs.push(`[daemon] exited (code=${code ?? "unknown"}, signal=${signal})`);
  });
  child.on("error", (err) => {
    daemonProcess = null;
    daemonStatus = "error";
    daemonLogs.push(`[daemon] error: ${err.message}`);
  });
}
function stopDaemon() {
  if (daemonProcess && !daemonProcess.killed) {
    daemonProcess.kill("SIGTERM");
    const pid = daemonProcess.pid;
    setTimeout(() => {
      try {
        if (pid)
          process.kill(pid, 0);
        if (daemonProcess && !daemonProcess.killed) {
          daemonProcess.kill("SIGKILL");
        }
      } catch {}
    }, 1e4);
  }
  daemonProcess = null;
  daemonStatus = "stopped";
}
async function call(onDone, _context, _args) {
  return /* @__PURE__ */ jsx_runtime.jsx(RemoteControlServer, {
    onDone
  });
}
var import_react, jsx_runtime, daemonProcess = null, daemonStatus = "stopped", daemonLogs, MAX_LOG_LINES = 50;
var init_remoteControlServer = __esm(() => {
  init_bridgeEnabled();
  init_bridgeConfig();
  init_types();
  init_Dialog();
  init_ListItem();
  init_overlayContext();
  init_src();
  init_useKeybinding();
  init_cliLaunch();
  init_errors();
  import_react = __toESM(require_react(), 1);
  jsx_runtime = __toESM(require_jsx_runtime(), 1);
  daemonLogs = [];
});
init_remoteControlServer();

export {
  call
};

//# debugId=275CB9C7821C481464756E2164756E21
//# sourceMappingURL=chunk-sb7wjk9d.js.map
