import type { ServerInfo } from '../types';

export function formatLanEndpoint(host: string, port: number): string {
  const h = host.trim().replace(/^https?:\/\//i, '').split('/')[0].split(':')[0];
  return `http://${h}:${port}`;
}

/** Distinct LAN URLs workers can use to reach this control server. */
export function lanEndpointCandidates(info: ServerInfo, portOverride?: number): string[] {
  const port = portOverride ?? info.port ?? 8989;
  const seen = new Set<string>();
  const out: string[] = [];

  const push = (raw: string) => {
    const u = raw.trim();
    if (!u || seen.has(u)) return;
    seen.add(u);
    out.push(u);
  };

  if (info.suggested_url?.trim()) {
    push(info.suggested_url.trim());
  }
  for (const ip of info.local_ips ?? []) {
    push(formatLanEndpoint(ip, port));
  }
  return out;
}
