import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const here = path.dirname(fileURLToPath(import.meta.url));
const source = path.join(here, "retell-native-import-template.json");
const output = path.join(here, "retell-native-import-ready.json");
const calApiKey = String(process.env.CAL_API_KEY || "").trim();
const eventTypeId = Number.parseInt(String(process.env.CAL_EVENT_TYPE_ID || ""), 10);

if (!calApiKey || calApiKey === "SET_CAL_API_KEY") {
  throw new Error("CAL_API_KEY is required.");
}
if (!Number.isInteger(eventTypeId) || eventTypeId <= 0) {
  throw new Error("CAL_EVENT_TYPE_ID must be a positive numeric Cal.com event type ID.");
}

const data = JSON.parse(fs.readFileSync(source, "utf8"));
for (const node of data.conversationFlow.nodes) {
  for (const tool of node.tools || []) {
    if (tool.type === "check_availability_cal" || tool.type === "book_appointment_cal") {
      tool.cal_api_key = calApiKey;
      tool.event_type_id = eventTypeId;
    }
  }
}

fs.writeFileSync(output, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
console.log(`Created ${path.basename(output)} with owner-only file permissions.`);
console.log("Import it into Retell, then delete it. Never share or upload this generated file.");
