import * as sidecar from '@@/sidecar-registry';
import { logger } from '../logger';
import { setOpenCodeSession } from './state';

// The OpenCode sidecar (officer-opencode) starts its `opencode serve` on a random port and reports it
// here on connect. We remember it so the OpenCode harness always routes to the current server. It also
// reports the OpenCode `ses_…` id it created for each live turn, which we persist so the next turn can
// resume it (`opencode run --session …`).

let serverPort: number | null = null;

sidecar.on('opencode:server', (msg) => {
  const port = (msg as { port?: number }).port;
  if (typeof port !== 'number') return;
  serverPort = port;
  logger.info('OpenCode sidecar server registered', { port, url: getOpenCodeServerUrl() });
});

sidecar.onOpenCodeSession((sessionKey, sessionId) => {
  setOpenCodeSession(sessionKey, sessionId);
});

/** The base URL of the sidecar's OpenCode server, or null if the sidecar hasn't reported in yet. */
export function getOpenCodeServerUrl(): string | null {
  return serverPort ? `http://127.0.0.1:${serverPort}` : null;
}
