/**
 * Idempotent Subito AI Guru setup against the ElevenLabs API. Safe to re-run;
 * every step converges (create-if-missing, update-in-place, merge-don't-
 * overwrite). Same pattern as kevo-setup.ts — distinct names everywhere, since
 * ElevenLabs secrets/tools are workspace-level and matched by name.
 *
 *   pnpm --filter @karma/core exec tsx src/cmd/guru-setup.ts
 *
 * Required env (apps/core/.env):
 *   ELEVENLABS_API_KEY                   workspace API key (shared with Kevo)
 *   SUBITO_AI_GURU_ELEVENLABS_AGENT_ID   the Guru agent
 *   GURU_TOOL_SHARED_SECRET              value for the X-Guru-Secret header
 *   GURU_PUBLIC_BASE_URL                 public base URL of core
 *                                        (falls back to KEVO_PUBLIC_BASE_URL)
 *
 * What it does:
 *   1. Upserts the workspace secret "guru_tool_shared_secret".
 *   2. Upserts the guru_* webhook tools (/v1/convai/tools), each with the
 *      secret header and conversation_id bound to system__conversation_id so
 *      the LLM never fills it.
 *   3. Merges the tool ids into the agent's prompt.tool_ids.
 *
 * Manual dashboard steps it cannot do: create the agent, enable text-only,
 * system prompt, knowledge base, post-call webhook (workspace-level).
 */
import { env } from "@/lib/env";
import { elevenLabsRequest } from "@/lib/elevenlabs/client";

const SECRET_NAME = "guru_tool_shared_secret";

const requireEnv = (key: string): string => {
  const v = env.GetString(key);
  if (!v) {
    console.error(`Missing required env var: ${key}`);
    process.exit(1);
  }
  return v;
};

async function ensureWorkspaceSecret(value: string): Promise<string> {
  const { secrets } = await elevenLabsRequest<{
    secrets: Array<{ secret_id: string; name: string }>;
  }>("/v1/convai/secrets");

  const existing = secrets.find((s) => s.name === SECRET_NAME);
  if (existing) {
    await elevenLabsRequest(`/v1/convai/secrets/${existing.secret_id}`, {
      method: "PATCH",
      body: { type: "update", name: SECRET_NAME, value },
    });
    console.log(`✓ workspace secret "${SECRET_NAME}" updated`);
    return existing.secret_id;
  }

  const created = await elevenLabsRequest<{ secret_id: string }>(
    "/v1/convai/secrets",
    { method: "POST", body: { type: "new", name: SECRET_NAME, value } },
  );
  console.log(`✓ workspace secret "${SECRET_NAME}" created`);
  return created.secret_id;
}

type ParamSpec = Record<
  string,
  { type: "string"; description: string; enum?: string[] }
>;

/** Every tool posts JSON with conversation_id bound to the system variable. */
const webhookTool = (opts: {
  name: string;
  description: string;
  url: string;
  secretId: string;
  required?: string[];
  params?: ParamSpec;
}) => ({
  tool_config: {
    type: "webhook",
    name: opts.name,
    description: opts.description,
    response_timeout_secs: 20,
    api_schema: {
      url: opts.url,
      method: "POST",
      request_headers: {
        "X-Guru-Secret": { secret_id: opts.secretId },
      },
      request_body_schema: {
        type: "object",
        required: ["conversation_id", ...(opts.required ?? [])],
        description: opts.description,
        properties: {
          ...(opts.params ?? {}),
          conversation_id: {
            type: "string",
            dynamic_variable: "system__conversation_id",
          },
        },
      },
    },
  },
});

const toolSpecs = (secretId: string, base: string) => [
  webhookTool({
    name: "guru_lookup_member",
    description:
      "Find a Karma member and their registration state. Use FIRST in almost every case, as soon " +
      "as you have the member's email, membership number or member number from the concierge. " +
      "Tells you whether the member exists in Viewpoint, whether they ever registered in the app " +
      "(app.registered=false usually means a first-time-login problem), and their account type and status. " +
      "When looked up by membership number, existing_cases lists console cases already open for this " +
      "member — mention them to the concierge instead of opening a duplicate. " +
      "Provide exactly one of email, membership_number or member_number.",
    url: `${base}/v1/guru/tools/lookup-member`,
    secretId,
    params: {
      email: {
        type: "string",
        description: "The member's email address, exactly as the concierge gave it.",
      },
      membership_number: {
        type: "string",
        description: "The Viewpoint account / membership number, e.g. 123456.",
      },
      member_number: {
        type: "string",
        description: "The individual member (contact) number.",
      },
    },
  }),
  webhookTool({
    name: "guru_member_overview",
    description:
      "Get a member account's last app session (when, which app, app version, device) and booking " +
      "counts. Use for login questions ('when did they last log in?', 'which app version?') after " +
      "you have the membership number. No session at all = the member never logged in.",
    url: `${base}/v1/guru/tools/member-overview`,
    secretId,
    required: ["membership_number"],
    params: {
      membership_number: {
        type: "string",
        description: "The Viewpoint account / membership number.",
      },
    },
  }),
  webhookTool({
    name: "guru_bookings",
    description:
      "List a member account's recent Viewpoint bookings (number, status, resort, dates, source). " +
      "Use for 'missing booking' or 'wrong booking' issues. Subito-made bookings also appear in " +
      "the member app itself; a booking visible here but not in the app is a sync/display issue.",
    url: `${base}/v1/guru/tools/bookings`,
    secretId,
    required: ["membership_number"],
    params: {
      membership_number: {
        type: "string",
        description: "The Viewpoint account / membership number.",
      },
    },
  }),
  webhookTool({
    name: "guru_booking",
    description:
      "Fetch one Viewpoint booking by its booking number. Use when the concierge quotes a " +
      "specific booking reference.",
    url: `${base}/v1/guru/tools/booking`,
    secretId,
    required: ["booking_number"],
    params: {
      booking_number: {
        type: "string",
        description: "The Viewpoint booking number.",
      },
    },
  }),
  webhookTool({
    name: "guru_points",
    description:
      "Get a member account's current points balance from Viewpoint. Use for 'wrong points shown' " +
      "or 'points missing' issues, then compare with what the member sees in the app.",
    url: `${base}/v1/guru/tools/points`,
    secretId,
    required: ["membership_number"],
    params: {
      membership_number: {
        type: "string",
        description: "The Viewpoint account / membership number.",
      },
    },
  }),
  webhookTool({
    name: "guru_entitlements",
    description:
      "Check a member account's contracts and points entitlements: contract validity/expiry, " +
      "inventory type (points/weeks), fee paid status, and every points entitlement line " +
      "(club, type LEVIED/BONUS, status ACTIVE/PENDING, issued, balance, expiry) across ALL " +
      "points clubs. Use for entitlement, fees, 'wrong points type' or 'membership expired?' " +
      "issues. Product-matrix flags (affiliate access, unit restrictions, Subito login allowed) " +
      "are not included — escalate when the issue depends on those.",
    url: `${base}/v1/guru/tools/entitlements`,
    secretId,
    required: ["membership_number"],
    params: {
      membership_number: {
        type: "string",
        description: "The Viewpoint account / membership number.",
      },
    },
  }),
  webhookTool({
    name: "guru_external_booking_status",
    description:
      "Check the Karma/Viewpoint side of an external-exchange booking (RCI, Weekly Escapes, " +
      "7Across, Getaways): presence in Viewpoint, status, dates as Karma holds them, amount " +
      "and currency. Use for 'RCI dates don't match' or 'vendor booking missing' issues. " +
      "Provide booking_number, or membership_number (with optional from/to) to list the " +
      "member's exchange bookings. The vendor's own system is NOT connected — for vendor-side " +
      "state, collect these details and escalate.",
    url: `${base}/v1/guru/tools/external-booking-status`,
    secretId,
    params: {
      booking_number: {
        type: "string",
        description: "The Viewpoint booking number, if the concierge has it.",
      },
      membership_number: {
        type: "string",
        description: "The Viewpoint account / membership number.",
      },
      from: { type: "string", description: "Optional arrival-date filter start, YYYY-MM-DD." },
      to: { type: "string", description: "Optional arrival-date filter end, YYYY-MM-DD." },
    },
  }),
  webhookTool({
    name: "guru_submission_log",
    description:
      "List the booking/hold requests a member submitted from the app or website, and whether " +
      "each one created a booking in Viewpoint. Use for 'member says they booked but nothing " +
      "shows' or 'request disappeared' issues. 'No Viewpoint booking recorded' means the " +
      "submission never became an on-hold booking — a real lead for escalation.",
    url: `${base}/v1/guru/tools/submission-log`,
    secretId,
    required: ["membership_number"],
    params: {
      membership_number: {
        type: "string",
        description: "The Viewpoint account / membership number.",
      },
      from: { type: "string", description: "Optional start date, YYYY-MM-DD." },
      to: { type: "string", description: "Optional end date, YYYY-MM-DD." },
    },
  }),
  webhookTool({
    name: "guru_availability",
    description:
      "Check unit availability at a resort for a date range and, more importantly, WHY it is " +
      "blocked: resort closure, blackout dates, two-year booking horizon, or simply no " +
      "inventory. Also lists the resort's currently active hot deals (with travel windows and " +
      "tier_restricted flag) and whether arrival is within 90 days. Use for 'member sees no " +
      "availability', 'hot deal not visible' or 'cannot book these dates' issues. resort_code " +
      "is the Viewpoint resort code (guru_bookings shows resort names; ask the concierge for " +
      "the code if unsure).",
    url: `${base}/v1/guru/tools/availability`,
    secretId,
    required: ["resort_code", "arrival", "departure"],
    params: {
      resort_code: {
        type: "string",
        description: "The Viewpoint resort code, e.g. 13.",
      },
      arrival: { type: "string", description: "Check-in date, YYYY-MM-DD." },
      departure: { type: "string", description: "Check-out date, YYYY-MM-DD." },
      unit_code: {
        type: "string",
        description: "Optional Viewpoint unit category code (e.g. T1) to narrow the check.",
      },
    },
  }),
  webhookTool({
    name: "guru_propose_action",
    description:
      "Propose a member-data fix. This NEVER changes anything itself: it puts a confirmation " +
      "card in the Console that only an authorised concierge can confirm. Use only after you " +
      "have diagnosed the issue and told the concierge what you intend to do. Supported actions: " +
      "PASSWORD_RESET (needs member_record_id from guru_lookup_member; a one-time password is " +
      "shown to the concierge on confirm), SEND_VERIFICATION_EDM (needs the member's email), " +
      "SYNC_PROFILE (needs profile_id from guru_lookup_member), RESEND_RCI_CONFIRMATION_EDM " +
      "(needs rci_unit_id — the RCI unit/booking id from the concierge — and member_record_id). " +
      "After calling, tell the " +
      "concierge to review the card and wait for the outcome. If they say it was refused, they " +
      "are not authorised — do not retry; escalate instead.",
    url: `${base}/v1/guru/tools/propose-action`,
    secretId,
    required: ["action_type", "member_ref", "summary"],
    params: {
      action_type: {
        type: "string",
        enum: [
          "PASSWORD_RESET",
          "SEND_VERIFICATION_EDM",
          "SYNC_PROFILE",
          "RESEND_RCI_CONFIRMATION_EDM",
        ],
        description: "The fix to propose.",
      },
      member_ref: {
        type: "string",
        description: "Membership number (preferred) or member number.",
      },
      summary: {
        type: "string",
        description:
          "One sentence: why this fix is needed. No contact details.",
      },
      member_record_id: {
        type: "string",
        description:
          "For PASSWORD_RESET: the member_record_id from guru_lookup_member.",
      },
      email: {
        type: "string",
        description:
          "For SEND_VERIFICATION_EDM: the member's email address, exactly as the concierge gave it.",
      },
      profile_id: {
        type: "string",
        description: "For SYNC_PROFILE: the profile_id from guru_lookup_member.",
      },
      rci_unit_id: {
        type: "string",
        description:
          "For RESEND_RCI_CONFIRMATION_EDM: the RCI unit/booking id, exactly as the concierge gave it.",
      },
    },
  }),
  webhookTool({
    name: "guru_ticket_history",
    description:
      "Get this case's ticket state and its full ClickUp history, including updates the product " +
      "team added after escalation. Call this FIRST whenever the concierge is continuing or " +
      "reopening an earlier case, before asking them to repeat anything. Covers ONLY this case " +
      "(plus other console cases for the same member in other_cases_for_member) — it cannot " +
      "search ClickUp, so never claim that no ClickUp task exists anywhere.",
    url: `${base}/v1/guru/tools/ticket-history`,
    secretId,
  }),
  webhookTool({
    name: "guru_update_ticket",
    description:
      "Record what this case is about on the Console ticket. Call once you know the member and " +
      "category, and again if the summary changes materially. category is one of: login, bookings, " +
      "points, entitlements, fees, other. summary: 1-2 plain sentences, no email addresses or " +
      "phone numbers. member_ref: the membership number (preferred) or member number.",
    url: `${base}/v1/guru/tools/update-ticket`,
    secretId,
    params: {
      member_ref: {
        type: "string",
        description: "Membership number (preferred) or member number.",
      },
      category: {
        type: "string",
        enum: ["login", "bookings", "points", "entitlements", "fees", "other"],
        description: "The issue category.",
      },
      summary: {
        type: "string",
        description:
          "One or two sentences describing the issue and state of diagnosis. No contact details.",
      },
    },
  }),
];

async function ensureTool(
  body: ReturnType<typeof webhookTool>,
  existingTools: Array<{ id: string; tool_config: { name: string } }>,
): Promise<string> {
  const name = body.tool_config.name;
  const existing = existingTools.find((t) => t.tool_config.name === name);
  if (existing) {
    await elevenLabsRequest(`/v1/convai/tools/${existing.id}`, {
      method: "PATCH",
      body,
    });
    console.log(`✓ tool "${name}" updated (${existing.id})`);
    return existing.id;
  }
  const created = await elevenLabsRequest<{ id: string }>("/v1/convai/tools", {
    method: "POST",
    body,
  });
  console.log(`✓ tool "${name}" created (${created.id})`);
  return created.id;
}

/**
 * Data collection drives the post-call pipeline: guru_resolution decides
 * RESOLVED / ESCALATED / stay OPEN. Id must match guru-postcall.service.ts.
 * Merge, never overwrite other fields on the agent.
 */
const DATA_COLLECTION: Record<string, { type: string; description: string }> =
  {
    guru_resolution: {
      type: "string",
      description:
        "How the case ended. 'resolved' only if the concierge's issue was fully explained or " +
        "fixed and the concierge acknowledged it. 'escalated' if it was handed to the product " +
        "team / a human, or involved entitlements, suspected bugs, or anything the agent could " +
        "not verify. 'unresolved' if the conversation ended without a clear outcome.",
    },
  };

async function ensureAnalysisConfig(agentId: string) {
  const agent = await elevenLabsRequest<{
    platform_settings?: { data_collection?: Record<string, unknown> };
  }>(`/v1/convai/agents/${agentId}`);
  await elevenLabsRequest(`/v1/convai/agents/${agentId}`, {
    method: "PATCH",
    body: {
      platform_settings: {
        data_collection: {
          ...(agent.platform_settings?.data_collection ?? {}),
          ...DATA_COLLECTION,
        },
      },
    },
  });
  console.log(
    `✓ data collection set (${Object.keys(DATA_COLLECTION).length} field)`,
  );
}

async function attachToolsToAgent(agentId: string, toolIds: string[]) {
  const agent = await elevenLabsRequest<{
    conversation_config: {
      agent: { prompt: Record<string, unknown> & { tool_ids?: string[] } };
    };
  }>(`/v1/convai/agents/${agentId}`);

  const prompt = agent.conversation_config.agent.prompt;
  const current = prompt.tool_ids ?? [];
  const missing = toolIds.filter((id) => !current.includes(id));
  if (!missing.length) {
    console.log("✓ all tools already attached to agent");
    return;
  }

  // Read-modify-write the whole prompt so nothing else on it is lost; drop
  // the deprecated inline `tools` list (mutually exclusive with tool_ids).
  const { tools: _deprecated, ...promptRest } = prompt as { tools?: unknown };
  await elevenLabsRequest(`/v1/convai/agents/${agentId}`, {
    method: "PATCH",
    body: {
      conversation_config: {
        agent: {
          prompt: { ...promptRest, tool_ids: [...current, ...missing] },
        },
      },
    },
  });
  console.log(`✓ ${missing.length} tool(s) attached to agent ${agentId}`);
}

async function main() {
  requireEnv("ELEVENLABS_API_KEY");
  const agentId = requireEnv("SUBITO_AI_GURU_ELEVENLABS_AGENT_ID");
  const secretValue = requireEnv("GURU_TOOL_SHARED_SECRET");
  const base = (
    process.env.GURU_PUBLIC_BASE_URL ||
    requireEnv("KEVO_PUBLIC_BASE_URL")
  ).replace(/\/$/, "");

  const secretId = await ensureWorkspaceSecret(secretValue);

  const { tools } = await elevenLabsRequest<{
    tools: Array<{ id: string; tool_config: { name: string } }>;
  }>("/v1/convai/tools");

  const ids: string[] = [];
  for (const spec of toolSpecs(secretId, base)) {
    ids.push(await ensureTool(spec, tools));
  }

  await attachToolsToAgent(agentId, ids);
  await ensureAnalysisConfig(agentId);

  console.log("\nDone. Manual dashboard steps (cannot be scripted):");
  console.log("  - Agent must allow text-only conversations.");
  console.log(
    "  - Workspace post-call webhook must point at /v1/kevo/webhooks/post-call (shared; routed by agent_id).",
  );
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
