#!/usr/bin/env node
import{join as e}from"path";import{spawn as t}from"child_process";const n=parseInt(process.env.OCTOCODE_RESEARCH_PORT||process.env.OCTOCODE_PORT||`1987`,10),r=`http://${process.env.OCTOCODE_RESEARCH_HOST||`localhost`}:${n}/health`,i=parseInt(process.env.OCTOCODE_INIT_TIMEOUT||`30000`,10),a=parseInt(process.env.OCTOCODE_POLL_INTERVAL||`500`,10);async function o(){try{let e=await fetch(r,{signal:AbortSignal.timeout(5e3)});return e.ok?await e.json():null}catch(e){return e instanceof Error&&!e.message.includes(`ECONNREFUSED`)&&console.error(`[server-init] Health check error: ${e.message}`),null}}function s(){return new Promise((n,r)=>{let i=new URL(`.`,import.meta.url).pathname,a=t(`node`,[e(i,`server.js`)],{stdio:`ignore`,cwd:i,detached:!0});a.on(`error`,e=>{console.error(`[server-init] Failed to start server: ${e.message}`),r(e)}),a.unref(),setTimeout(()=>{console.log(`[server-init] Spawned detached server process (pid: ${a.pid})`),n()},100)})}async function c(){let e=Date.now(),t=a;for(;Date.now()-e<i;){let e=await o();if(e?.status===`ok`)return!0;e?.status===`initializing`&&console.log(`[server-init] Server initializing...`),await new Promise(e=>setTimeout(e,t)),t=Math.min(t*1.5,2e3)}return!1}async function l(){let e=await o();e?.status===`ok`&&(console.log(`ok`),process.exit(0)),e?.status===`initializing`&&(console.log(`[server-init] Server is initializing, waiting...`),await c()?(console.log(`ok`),process.exit(0)):(console.error(`[server-init] ERROR: Server stuck in initializing state`),process.exit(1))),console.log(`[server-init] Server not running, starting detached daemon...`);try{await s()}catch{console.error(`[server-init] ERROR: Failed to spawn server process`),process.exit(1)}await c()||(console.error(`[server-init] ERROR: Server failed to start within timeout`),process.exit(1)),console.log(`ok`),process.exit(0)}l();export{};