/**
 * Idempotent Kevo setup against the ElevenLabs API. Safe to re-run; every
 * step converges (create-if-missing, update-in-place, merge-don't-overwrite).
 *
 *   pnpm --filter @karma/core exec tsx src/cmd/kevo-setup.ts
 *
 * Required env (apps/core/.env):
 *   ELEVENLABS_API_KEY        workspace API key
 *   ELEVENLABS_AGENT_ID       the Kevo agent
 *   KEVO_TOOL_SHARED_SECRET   value for the X-Kevo-Secret header
 *   KEVO_PUBLIC_BASE_URL      public base URL of core, e.g. https://api.example.com
 *
 * What it does (endpoints verified in docs/kevo-flagging/API_NOTES.md):
 *   1. Upserts the workspace secret "kevo_tool_shared_secret".
 *   2. Upserts the "flag_issue" webhook tool (/v1/convai/tools), with the
 *      secret as a header and conversation_id/member_id bound to dynamic
 *      variables so the LLM never fills them.
 *   3. Merges the tool id into the agent's prompt.tool_ids (read-modify-write
 *      of the prompt; never drops existing tools or knowledge base entries).
 *
 * Post-call webhook registration is workspace-level in the ElevenLabs
 * dashboard and cannot be scripted — see docs/kevo-flagging/README.md.
 */
import { env } from "@/lib/env";
import { elevenLabsRequest } from "@/lib/elevenlabs/client";
import {
  DATA_COLLECTION_IDS,
  EVAL_CRITERIA_IDS,
} from "@/internal/kevo/kevo-postcall.service";

const TOOL_NAME = "flag_issue";
const SECRET_NAME = "kevo_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;
}

const toolConfig = (secretId: string, flagIssueUrl: string) => ({
  tool_config: {
    type: "webhook",
    name: TOOL_NAME,
    description:
      "Report a problem in this conversation to the Karma team so a human can review and fix it. " +
      "Call this whenever: you cannot find an answer in your knowledge; you are unsure and would " +
      "have to guess; the member says your information is wrong; or the member asks to change " +
      "account details you cannot change (for example a wrong mobile number or email). " +
      "After calling it, tell the member their issue was passed to the team and give them the " +
      "reference number from the response. Never invent an answer instead of calling this tool. " +
      "Do not include full phone numbers, email addresses or other contact details in any field.",
    response_timeout_secs: 10,
    api_schema: {
      url: flagIssueUrl,
      method: "POST",
      request_headers: {
        "X-Kevo-Secret": { secret_id: secretId },
      },
      request_body_schema: {
        type: "object",
        required: ["category", "member_question", "conversation_id"],
        description: "Details of the issue being flagged for human review.",
        properties: {
          category: {
            type: "string",
            enum: [
              "KNOWLEDGE_GAP",
              "WRONG_INFO",
              "DATA_UPDATE_REQUEST",
              "ESCALATION",
              "OTHER",
            ],
            description:
              "KNOWLEDGE_GAP: you did not know the answer. WRONG_INFO: you gave " +
              "incorrect information or the member disputed it. DATA_UPDATE_REQUEST: " +
              "the member wants account data changed that you cannot edit. " +
              "ESCALATION: a human must follow up. OTHER: anything else.",
          },
          member_question: {
            type: "string",
            description:
              "The member's question or request, summarised accurately in one or two sentences. No contact details.",
          },
          agent_answer: {
            type: "string",
            description:
              "What you said (or would have said) in response. Empty if you had no answer.",
          },
          member_claim: {
            type: "string",
            description:
              "If the member says your information is wrong: what they say is correct instead.",
          },
          entity: {
            type: "string",
            description:
              "The property, amenity or topic concerned, e.g. 'Karma Beach' or 'Karma Kandara'.",
          },
          requested_change: {
            type: "string",
            description:
              "For DATA_UPDATE_REQUEST: which field the member wants changed, e.g. 'mobile number incorrect'. Never the new value itself.",
          },
          conversation_id: {
            type: "string",
            dynamic_variable: "system__conversation_id",
          },
          member_id: {
            type: "string",
            dynamic_variable: "member_id",
          },
        },
      },
    },
  },
});

async function ensureTool(secretId: string, flagIssueUrl: string) {
  const { tools } = await elevenLabsRequest<{
    tools: Array<{ id: string; tool_config: { name: string } }>;
  }>("/v1/convai/tools");

  const body = toolConfig(secretId, flagIssueUrl);
  const existing = tools.find((t) => t.tool_config.name === TOOL_NAME);
  if (existing) {
    await elevenLabsRequest(`/v1/convai/tools/${existing.id}`, {
      method: "PATCH",
      body,
    });
    console.log(`✓ tool "${TOOL_NAME}" updated (${existing.id})`);
    return existing.id;
  }

  const created = await elevenLabsRequest<{ id: string }>("/v1/convai/tools", {
    method: "POST",
    body,
  });
  console.log(`✓ tool "${TOOL_NAME}" created (${created.id})`);
  return created.id;
}

async function attachToolToAgent(agentId: string, toolId: 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 toolIds = prompt.tool_ids ?? [];
  if (toolIds.includes(toolId)) {
    console.log("✓ tool already attached to agent");
    return;
  }

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

/**
 * Evaluation criteria are written so that FAILURE always means "create a
 * flag" — the post-call worker flags on result === "failure".
 * Ids must stay in sync with kevo-postcall.service.ts.
 */
const EVALUATION_CRITERIA = [
  {
    id: EVAL_CRITERIA_IDS.answeredCorrectly,
    name: "Answered correctly without gaps",
    type: "prompt",
    conversation_goal_prompt:
      "Mark success only if the agent answered every member question using its verified " +
      "knowledge, without admitting it did not know, guessing, or giving information it was " +
      "not sure about. Mark failure if the agent lacked knowledge about any property, amenity " +
      "or topic the member asked about.",
  },
  {
    id: EVAL_CRITERIA_IDS.notDisputed,
    name: "Member did not dispute information",
    type: "prompt",
    conversation_goal_prompt:
      "Mark success only if the member never said or implied that the agent's information was " +
      "wrong, outdated or inaccurate. Mark failure if the member corrected the agent or " +
      "disputed any fact the agent stated.",
  },
  {
    id: EVAL_CRITERIA_IDS.nothingUnresolved,
    name: "No unresolved member request",
    type: "prompt",
    conversation_goal_prompt:
      "Mark success only if every request the member made was either fulfilled or explicitly " +
      "handed over (flagged to the team with a reference number). Mark failure if a request " +
      "was left unresolved without a handover — for example an account data change, a booking " +
      "action or a complaint the agent could not deal with.",
  },
];

const DATA_COLLECTION: Record<
  string,
  { type: string; description: string }
> = {
  [DATA_COLLECTION_IDS.knowledgeGapTopic]: {
    type: "string",
    description:
      "If the agent could not answer a question or lacked knowledge: the specific property, " +
      "amenity or topic concerned (e.g. 'Karma Beach'). Empty if there was no knowledge gap.",
  },
  [DATA_COLLECTION_IDS.disputedFact]: {
    type: "string",
    description:
      "If the member said the agent's information was wrong: the fact in dispute and what the " +
      "member claims is correct instead. Never include phone numbers or email addresses. " +
      "Empty if nothing was disputed.",
  },
  [DATA_COLLECTION_IDS.dataChangeRequested]: {
    type: "string",
    description:
      "If the member asked to change account data the agent cannot edit: which field needs " +
      "changing (e.g. 'mobile number incorrect'). Describe the field only — never the old or " +
      "new value. Empty if no such request was made.",
  },
};

async function ensureAnalysisConfig(agentId: string) {
  const agent = await elevenLabsRequest<{
    platform_settings?: {
      evaluation?: { criteria?: Array<{ id: string }> };
      data_collection?: Record<string, unknown>;
    };
  }>(`/v1/convai/agents/${agentId}`);

  const settings = agent.platform_settings ?? {};
  const ourIds = new Set<string>(EVALUATION_CRITERIA.map((c) => c.id));
  // Merge, never overwrite: keep every criterion/field we don't own.
  const otherCriteria = (settings.evaluation?.criteria ?? []).filter(
    (c) => !ourIds.has(c.id),
  );
  const mergedDataCollection = {
    ...(settings.data_collection ?? {}),
    ...DATA_COLLECTION,
  };

  await elevenLabsRequest(`/v1/convai/agents/${agentId}`, {
    method: "PATCH",
    body: {
      platform_settings: {
        evaluation: { criteria: [...otherCriteria, ...EVALUATION_CRITERIA] },
        data_collection: mergedDataCollection,
      },
    },
  });
  console.log(
    `✓ analysis config set (${EVALUATION_CRITERIA.length} criteria, ${Object.keys(DATA_COLLECTION).length} data fields)`,
  );
}

async function main() {
  const agentId = requireEnv("ELEVENLABS_AGENT_ID");
  const sharedSecret = requireEnv("KEVO_TOOL_SHARED_SECRET");
  const publicBase = requireEnv("KEVO_PUBLIC_BASE_URL").replace(/\/$/, "");
  requireEnv("ELEVENLABS_API_KEY");

  const flagIssueUrl = `${publicBase}/v1/kevo/tools/flag-issue`;
  console.log(`Kevo setup → agent ${agentId}, tool URL ${flagIssueUrl}`);

  const secretId = await ensureWorkspaceSecret(sharedSecret);
  const toolId = await ensureTool(secretId, flagIssueUrl);
  await attachToolToAgent(agentId, toolId);
  await ensureAnalysisConfig(agentId);
  console.log("Done. Remember the manual steps in docs/kevo-flagging/README.md");
}

main().catch((err) => {
  console.error("Kevo setup failed:", err);
  process.exit(1);
});
