import { isAbsolute, join, resolve } from "node:path";

function port(value, fallback, name) {
  const parsed = Number(value ?? fallback);
  if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
    throw new Error(`${name} must be an integer between 1 and 65535`);
  }
  return String(parsed);
}

/** Control-plane origin. Conversation routes are served here; one-click start has no second port. */
export function controlPlaneOrigin(env = {}) {
  const host = env.API_HOST?.trim() || "127.0.0.1";
  return `http://${host}:${port(env.API_PORT, 8787, "API_PORT")}`;
}

function chatProxyTarget(env) {
  const explicit = env.CHAT_PROXY_TARGET?.trim();
  if (explicit) return explicit.replace(/\/$/u, "");
  return controlPlaneOrigin(env);
}

export function resolveStackRuntimeConfig(env = process.env) {
  return {
    API_HOST: env.API_HOST?.trim() || "127.0.0.1",
    API_PORT: port(env.API_PORT, 8787, "API_PORT"),
    WEB_HOST: env.WEB_HOST?.trim() || "127.0.0.1",
    WEB_PORT: port(env.WEB_PORT, 3000, "WEB_PORT"),
    CHAT_PROXY_TARGET: chatProxyTarget(env),
  };
}

/** Absolute session database shared with the control plane (cwd is apps/api). */
export function resolveControlPlaneMetadataPath(env, apiDir) {
  const configured = env.METADATA_DB_PATH?.trim();
  if (configured) {
    return isAbsolute(configured) ? configured : resolve(apiDir, configured);
  }
  const storage = env.STORAGE_ROOT_DIR?.trim() || "storage";
  const root = isAbsolute(storage) ? storage : resolve(apiDir, storage);
  return join(root, "metadata", "workbench.sqlite");
}

export function webProcessEnvironment(config) {
  return { HOSTNAME: config.WEB_HOST, PORT: config.WEB_PORT };
}

export function formatStackEndpoints(config, enabled) {
  const lines = ["DataFoundry endpoints:"];
  if (enabled.startWeb) lines.push(`  Web: http://127.0.0.1:${config.WEB_PORT}`);
  if (enabled.startApi) {
    lines.push(`  API: http://${config.API_HOST}:${config.API_PORT}`);
    lines.push(`  Chat: ${config.CHAT_PROXY_TARGET}/api/copilotkit`);
  }
  return lines.join("\n");
}