import { getOpenCodeServerUrl } from './sidecar-server';

// The OpenCode server is owned by the officer-opencode sidecar, which starts `opencode serve` on a
// random port (cwd = DATA_PATH/opencode-sidecar) and reports it to the API (getOpenCodeServerUrl).
// All OpenCode HTTP traffic routes to whatever port the sidecar last reported.

export async function isServerHealthy(): Promise<boolean> {
  const baseUrl = getOpenCodeServerUrl();
  if (!baseUrl) return false;
  try {
    const res = await fetch(`${baseUrl}/api/health`, { signal: AbortSignal.timeout(3000) });
    return res.ok;
  } catch {
    return false;
  }
}

/** The base URL of the OpenCode server the sidecar is running. Throws if it hasn't reported in yet. */
export async function ensureServer(): Promise<{ baseUrl: string }> {
  const baseUrl = getOpenCodeServerUrl();
  if (!baseUrl) throw new Error('OpenCode sidecar server not available yet');
  return { baseUrl };
}
