import { loadVoiceAgentConfig } from "./config.ts";
import { McpToolClient } from "./mcp-tool-client.ts";
import { defaultAuditLogPath, reconcileAuditLog } from "./audit-store.ts";

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

const auditPath = process.env.VOICE_AGENT_AUDIT_LOG ?? defaultAuditLogPath();
const outputPath =
  process.env.VOICE_AGENT_RECONCILED_AUDIT_LOG ?? `${auditPath.replace(/\.jsonl$/, "")}.reconciled.jsonl`;
const now = new Date();
const defaultFrom = new Date(now.getTime() - 24 * 60 * 60 * 1000);
const dateFrom = process.env.RC_RECONCILE_DATE_FROM ?? defaultFrom.toISOString();
const dateTo = process.env.RC_RECONCILE_DATE_TO ?? now.toISOString();

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

try {
  const result = await reconcileAuditLog({
    auditPath,
    outputPath,
    ringCentral: admin,
    dateFrom,
    dateTo,
  });
  console.log(JSON.stringify({ ok: true, ...result }, null, 2));
} finally {
  await admin.close();
}
