import { loadVoiceAgentConfig } from "./config.ts";
import { McpToolClient } from "./mcp-tool-client.ts";
import { checkAllMcpEndpoints } from "./mcp-readiness.ts";
import {
  describeSipDiscoveryResult,
  discoverRingCentralSipDevice,
} from "./ringcentral-sip-discovery.ts";

const config = loadVoiceAgentConfig();
const checks: Array<{ name: string; ok: boolean; detail?: string }> = [];

checks.push({
  name: "voice_provider_credentials",
  ok:
    config.defaultVoiceProvider === "openai_realtime"
      ? Boolean(config.openai.apiKey)
      : Boolean(config.xai.apiKey && config.xai.phiAllowed),
  detail:
    config.defaultVoiceProvider === "openai_realtime"
      ? "requires OPENAI_API_KEY"
      : "requires XAI_API_KEY and XAI_PHI_ALLOWED=1",
});

if (config.voiceProviderFailover) {
  checks.push({
    name: "voice_provider_failover",
    ok:
      config.defaultVoiceProvider === "openai_realtime" &&
      Boolean(config.xai.apiKey && config.xai.phiAllowed),
    detail:
      "VOICE_PROVIDER_FAILOVER=1 requires VOICE_PROVIDER=openai_realtime, XAI_API_KEY, and XAI_PHI_ALLOWED=1.",
  });
}

checks.push({
  name: "human_transfer_destination",
  ok: Boolean(process.env.HUMAN_TRANSFER_DESTINATION?.trim()),
  detail: "requires HUMAN_TRANSFER_DESTINATION for staff escalations",
});

try {
  await import("ringcentral-softphone");
  checks.push({ name: "ringcentral_softphone_package", ok: true });
} catch (err) {
  checks.push({
    name: "ringcentral_softphone_package",
    ok: false,
    detail: err instanceof Error ? err.message : String(err),
  });
}

const readiness = await checkAllMcpEndpoints([
  config.mcp.advancedmd,
  config.mcp.ringcentral,
  config.mcp.ringcentralAdmin,
]);
checks.push({
  name: "hosted_mcp_transport",
  ok: readiness.every((result) => result.ok),
  detail: readiness
    .filter((result) => !result.ok)
    .map((result) => `${result.name}: ${result.error ?? result.status}`)
    .join("; "),
});

if (config.ringCentralSip) {
  checks.push({ name: "ringcentral_sip_env", ok: true });
} else if (!config.mcp.ringcentralAdmin.bearerToken) {
  checks.push({
    name: "ringcentral_sip_device",
    ok: false,
    detail: "No SIP env and MCP_BEARER_TOKEN is unavailable for RingCentral Admin discovery.",
  });
} else {
  const admin = new McpToolClient({
    name: config.mcp.ringcentralAdmin.name,
    mcpUrl: config.mcp.ringcentralAdmin.mcpUrl,
    bearerToken: config.mcp.ringcentralAdmin.bearerToken,
  });
  try {
    const discovery = await discoverRingCentralSipDevice({ admin });
    checks.push({
      name: "ringcentral_sip_device",
      ok: discovery.ok,
      detail: describeSipDiscoveryResult(discovery),
    });
  } finally {
    await admin.close();
  }
}

const ok = checks.every((check) => check.ok);
console.log(JSON.stringify({ ok, checks }, null, 2));
process.exit(ok ? 0 : 1);
