import { FakeVoiceProvider } from "./fake-voice-provider.ts";
import { VoicePolicyProxy, type SchedulingToolPort } from "./policy-proxy.ts";
import { RingCentralBridge } from "./ringcentral-bridge.ts";
import { SimulatedRingCentralClient } from "./simulated-media.ts";

const utterance = process.argv.slice(2).join(" ") || "I need to reschedule my appointment";
const events: string[] = [];

const scheduling: SchedulingToolPort = {
  async verifyPatientIdentity(args) {
    events.push(`tool:verify_patient_identity:${JSON.stringify(args)}`);
    return { ok: true, action: "continue", message: "Identity verified." };
  },
  async findRescheduleOptions(args) {
    events.push(`tool:find_reschedule_options:${JSON.stringify(args)}`);
    return {
      ok: true,
      action: "offer_slots",
      message: "Two safe same-provider slots are available.",
      data: {
        slots: [
          { slot_id: "slot-1", starts_at: "2026-06-03T15:00:00-05:00" },
          { slot_id: "slot-2", starts_at: "2026-06-04T10:00:00-05:00" },
        ],
      },
    };
  },
  async requestReschedule() {
    events.push("tool:request_reschedule");
    return {
      ok: false,
      action: "approval_required",
      message: "Writes are disabled in the simulator.",
    };
  },
  async createCallback(args) {
    events.push(`tool:create_callback:${JSON.stringify(args)}`);
    return { ok: true, action: "callback_required", message: "Callback queued." };
  },
  async transferToStaff(args) {
    events.push(`tool:transfer_to_staff:${JSON.stringify(args)}`);
    return { ok: true, action: "transfer_to_staff", message: "Transferred." };
  },
};

const client = new SimulatedRingCentralClient();
const policyProxy = new VoicePolicyProxy(scheduling);
const bridge = new RingCentralBridge(client, {
  voiceProvider: new FakeVoiceProvider("openai_realtime"),
  policyProxy,
  humanTransferDestination: "+15550999000",
  instructions: "You are Exult's scheduling backup voice agent.",
  onAudit: (record) => {
    events.push(`audit:${record.disposition}`);
  },
});
bridge.start();

const call = await client.receiveCall({
  callId: "simulated-call-1",
  callerNumber: "+19725550100",
  calledNumber: "+15550999000",
  extensionId: "AI Scheduling Backup",
});
await call.callerSays(utterance);
await call.close();

console.log(
  JSON.stringify(
    {
      ok: true,
      answered: call.answered,
      transferredTo: call.transferredTo ?? null,
      events,
    },
    null,
    2,
  ),
);
