import { loadVoiceAgentConfig } from "./config.ts";
import { McpToolClient } from "./mcp-tool-client.ts";
import {
  buildAiSchedulingProvisioningPlan,
  executeAiSchedulingExtensionProvisioning,
} from "./ringcentral-provisioning-plan.ts";

const config = loadVoiceAgentConfig();
const endpoint = config.mcp.ringcentralAdmin;
if (!endpoint.bearerToken) {
  throw new Error("MCP_BEARER_TOKEN is required for RingCentral provisioning planning.");
}

const admin = new McpToolClient({
  name: endpoint.name,
  mcpUrl: endpoint.mcpUrl,
  bearerToken: endpoint.bearerToken,
});

try {
  const common = {
    admin,
    extensionNumber: process.env.RC_AI_EXTENSION_NUMBER,
    extensionName: process.env.RC_AI_EXTENSION_NAME,
    email: process.env.RC_AI_EXTENSION_EMAIL,
    deviceName: process.env.RC_AI_DEVICE_NAME,
  };
  if (process.env.RC_PROVISION_EXECUTE === "1" || process.env.RC_PROVISION_DRY_RUN === "1") {
    const approvalText = await approvalTextFromEnvOrFile();
    const result = await executeAiSchedulingExtensionProvisioning({
      ...common,
      approvalText,
      execute: process.env.RC_PROVISION_EXECUTE === "1",
    });
    console.log(JSON.stringify(result, null, 2));
    process.exit(result.ok ? 0 : 1);
  }

  const plan = await buildAiSchedulingProvisioningPlan(common);
  console.log(JSON.stringify(plan, null, 2));
  process.exit(plan.ok ? 0 : 1);
} finally {
  await admin.close();
}

async function approvalTextFromEnvOrFile(): Promise<string> {
  if (process.env.RC_APPROVAL_TEXT) return process.env.RC_APPROVAL_TEXT;
  if (process.env.RC_APPROVAL_TEXT_FILE) {
    return await Bun.file(process.env.RC_APPROVAL_TEXT_FILE).text();
  }
  throw new Error("RC_APPROVAL_TEXT or RC_APPROVAL_TEXT_FILE is required for provisioning dry-run/execute.");
}
