import type { Kysely } from "kysely";
import { logError, logInfo } from "@/lib/logger";
import { elevenLabsRequest } from "@/lib/elevenlabs/client";
import {
  addClickUpTaskTags,
  createClickUpTask,
  createClickUpTaskComment,
} from "@/lib/clickup/client";
import { GuruRepositoryFromDb } from "./guru.repository";
import { redactSensitive } from "@/internal/kevo/kevo.service";

/**
 * Guru post-call processing (docs/subito-ai-guru.md §2, §4 — ClickUp is the
 * system of record). Runs inside a BullMQ job; retries come from the queue.
 *
 * After every Guru conversation:
 *  1. Update the local ticket (summary, resolution, status) from the
 *     ElevenLabs analysis.
 *  2. Ensure the ClickUp task exists in the Guru list, then post the full
 *     (redacted) conversation as comments — batched here, not per message,
 *     per the meeting notes' rate-limit concern.
 *  3. Tag auto-resolved vs escalated; assign escalations to the PM/TPM.
 *
 * Comment-text PII: every transcript line passes through redactSensitive.
 */

// Data-collection ids — must match what guru-setup.ts configures.
export const GURU_DATA_COLLECTION_IDS = {
  resolution: "guru_resolution",
} as const;

const COMMENT_CHUNK = 8_000;

interface GuruConversationDetail {
  conversation_id: string;
  metadata?: { start_time_unix_secs?: number; call_duration_secs?: number };
  transcript?: Array<{ role?: string; message?: string | null }>;
  analysis?: {
    transcript_summary?: string;
    data_collection_results?: Record<
      string,
      { data_collection_id?: string; value?: unknown }
    >;
  };
}

const asText = (v: unknown): string | undefined => {
  if (typeof v !== "string") return undefined;
  const t = v.trim();
  return t ? t : undefined;
};

export const renderTranscript = (
  turns: Array<{ role?: string; message?: string | null }>,
): string =>
  turns
    .filter((t) => t.message)
    .map(
      (t) =>
        `${t.role === "user" ? "Concierge" : "Guru"}: ${redactSensitive(t.message as string)}`,
    )
    .join("\n\n");

/** Split on line boundaries so no comment exceeds the chunk size. */
export const chunkText = (text: string, max = COMMENT_CHUNK): string[] => {
  if (text.length <= max) return text ? [text] : [];
  const chunks: string[] = [];
  let current = "";
  for (const rawLine of text.split("\n")) {
    // A single line longer than the limit is hard-split, not truncated.
    const pieces: string[] = [];
    for (let i = 0; i < rawLine.length || pieces.length === 0; i += max) {
      pieces.push(rawLine.slice(i, i + max));
    }
    for (const line of pieces) {
      if (current && current.length + line.length + 1 > max) {
        chunks.push(current);
        current = "";
      }
      current = current ? `${current}\n${line}` : line;
    }
  }
  if (current) chunks.push(current);
  return chunks;
};

export async function processGuruPostCall(
  pool: Kysely<unknown>,
  conversationId: string,
): Promise<void> {
  const repo = GuruRepositoryFromDb(pool);

  const ticket = await repo.getTicketByConversation(conversationId);
  if (!ticket) {
    // Not an error: a Guru conversation that was never bound to a ticket
    // (e.g. the Console tab closed before binding). Nothing to update.
    logInfo(`[Guru] post-call ${conversationId}: no ticket bound, skipping`);
    return;
  }

  // Idempotency: webhook retries re-enqueue the same jobId, but a *failed*
  // attempt retries legitimately. Skip only if this conversation was already
  // fully processed. (Audit writes are best-effort — a lost audit row can at
  // worst duplicate a transcript comment. ponytail: acceptable.)
  const { entries } = await repo.listAudit({
    ticket_id: ticket.id,
    page: 1,
    limit: 100,
  });
  const already = entries.some(
    (e) =>
      e.action === "ticket.postcall_processed" &&
      (e.metadata as { conversation_id?: string } | null)?.conversation_id ===
        conversationId,
  );
  if (already) {
    logInfo(`[Guru] post-call ${conversationId}: already processed`);
    return;
  }

  const detail = await elevenLabsRequest<GuruConversationDetail>(
    `/v1/convai/conversations/${conversationId}`,
  );

  const summary = detail.analysis?.transcript_summary
    ? redactSensitive(detail.analysis.transcript_summary).slice(0, 2000)
    : null;
  const resolutionRaw = asText(
    detail.analysis?.data_collection_results?.[
      GURU_DATA_COLLECTION_IDS.resolution
    ]?.value,
  )?.toLowerCase();

  // ---- 1. local ticket state ----
  const resolved = resolutionRaw === "resolved";
  const escalated = resolutionRaw === "escalated";
  await repo.updateTicket(ticket.id, {
    ...(summary && !ticket.summary ? { summary } : {}),
    ...(resolved
      ? {
          status: "RESOLVED",
          resolution: "AUTO_RESOLVED",
          resolved_at: new Date(),
        }
      : {}),
    ...(escalated
      ? { status: "ESCALATED", resolution: "ESCALATED" }
      : {}),
  });

  // ---- 2. ClickUp task + transcript comments ----
  const listId = process.env.GURU_CLICKUP_LIST_ID;
  let taskId = ticket.clickup_task_id;
  if (!listId) {
    logError(
      "[Guru] GURU_CLICKUP_LIST_ID is not set — ticket updated locally, ClickUp skipped",
    );
  } else {
    try {
      if (!taskId) {
        const consoleBase =
          process.env.CONSOLE_BASE_URL || "http://localhost:3002";
        const assigneeRaw = process.env.GURU_CLICKUP_PM_ASSIGNEE?.trim();
        const assignee = assigneeRaw ? Number(assigneeRaw) : NaN;
        const task = await createClickUpTask({
          listId,
          name: `[${ticket.reference}] ${ticket.category ?? "support case"}${
            ticket.member_ref ? ` — member ${ticket.member_ref}` : ""
          }`,
          markdown_description: [
            summary ?? ticket.summary ?? "Concierge support case.",
            "",
            `**Console ticket:** ${consoleBase}/admin/guru/tickets/${ticket.reference}`,
            `**Concierge:** ${ticket.concierge_email}`,
            ...(ticket.member_ref
              ? [`**Member:** ${ticket.member_ref}`]
              : []),
          ].join("\n"),
          tags: ["guru"],
          ...(escalated && Number.isFinite(assignee)
            ? { assignees: [assignee] }
            : {}),
        });
        taskId = task.id;
        await repo.updateTicket(ticket.id, {
          clickup_task_id: task.id,
          clickup_task_url: task.url,
        });
        await repo.insertAudit({
          ticket_id: ticket.id,
          action: "clickup.created",
          actor_email: ticket.concierge_email,
          member_ref: ticket.member_ref,
          clickup_task_id: task.id,
          success: true,
        });
      }

      const transcript = renderTranscript(detail.transcript ?? []);
      const header = `Conversation ${conversationId} — ${
        detail.metadata?.start_time_unix_secs
          ? new Date(
              detail.metadata.start_time_unix_secs * 1000,
            ).toISOString()
          : "time unknown"
      }${resolutionRaw ? ` — ${resolutionRaw}` : ""}`;
      const chunks = chunkText(transcript);
      if (!chunks.length) {
        await createClickUpTaskComment(taskId, `${header}\n(no transcript)`);
      } else {
        for (let i = 0; i < chunks.length; i++) {
          await createClickUpTaskComment(
            taskId,
            `${header}${chunks.length > 1 ? ` (${i + 1}/${chunks.length})` : ""}\n\n${chunks[i]}`,
          );
        }
      }

      if (resolved) await addClickUpTaskTags(taskId, ["auto-resolved"]);
      if (escalated) await addClickUpTaskTags(taskId, ["escalated"]);
    } catch (err) {
      // Let the queue retry — the processed-marker below is only written on
      // full success, so a retry re-runs ClickUp (task creation is guarded by
      // clickup_task_id having been saved).
      throw err;
    }
  }

  // ---- 3. Viewpoint closed log (spec §3) ----
  // After every conversation that touched a member, a summary note goes on
  // the member's Viewpoint record. member_ref is the Viewpoint account id
  // (tool descriptions steer the agent to use the membership number).
  // CLOSED-on-create is unverified against the real API (docs §7.3) —
  // fall back to OPEN on a 4xx so the note is never silently lost.
  if (ticket.member_ref) {
    const actionLines = (
      await repo.listActionsForTicket(ticket.id)
    )
      .filter((a) => a.status === "EXECUTED")
      .map((a) => `- ${a.summary}`);
    const comment = [
      `Karma Subito AI Guru case ${ticket.reference} (concierge: ${ticket.concierge_email})`,
      summary ?? ticket.summary ?? "No summary.",
      ...(actionLines.length ? ["Actions taken:", ...actionLines] : []),
      ...(resolutionRaw ? [`Outcome: ${resolutionRaw}`] : []),
      ...(taskId ? [`ClickUp task: ${taskId}`] : []),
    ].join("\n");

    try {
      const { ViewpointMember } = await import("@karma/viewpoint-sdk/member");
      const vp = new ViewpointMember();
      try {
        await vp.createAuditLog({
          accountID: ticket.member_ref,
          subject: `Karma Subito AI Guru — ${ticket.category ?? "support"} (${ticket.reference})`,
          comment: redactSensitive(comment),
          status: "CLOSED",
        });
        await repo.insertAudit({
          ticket_id: ticket.id,
          action: "viewpoint.logged",
          actor_email: ticket.concierge_email,
          member_ref: ticket.member_ref,
          success: true,
          metadata: { conversation_id: conversationId, log_status: "CLOSED" },
        });
      } catch (err) {
        // ViewpointApiError carries .status; anything else (network, missing
        // account) re-throws to the outer catch.
        const status = (err as { status?: number }).status;
        const is4xx =
          typeof status === "number" && status >= 400 && status < 500;
        if (!is4xx) throw err;
        // CLOSED rejected — write it OPEN instead of losing the note.
        await vp.createAuditLog({
          accountID: ticket.member_ref,
          subject: `Karma Subito AI Guru — ${ticket.category ?? "support"} (${ticket.reference})`,
          comment: redactSensitive(comment),
          status: "OPEN",
        });
        await repo.insertAudit({
          ticket_id: ticket.id,
          action: "viewpoint.logged",
          actor_email: ticket.concierge_email,
          member_ref: ticket.member_ref,
          success: true,
          metadata: {
            conversation_id: conversationId,
            log_status: "OPEN",
            fallback: "CLOSED rejected by Viewpoint",
          },
        });
      }
    } catch (err) {
      logError(`[Guru] Viewpoint log failed for ${ticket.reference}: ${err}`);
      await repo.insertAudit({
        ticket_id: ticket.id,
        action: "viewpoint.log_failed",
        actor_email: ticket.concierge_email,
        member_ref: ticket.member_ref,
        success: false,
        metadata: { conversation_id: conversationId },
      });
    }
  }

  // ---- 4. processed marker ----
  await repo.insertAudit({
    ticket_id: ticket.id,
    action: "ticket.postcall_processed",
    actor_email: ticket.concierge_email,
    member_ref: ticket.member_ref,
    clickup_task_id: taskId ?? null,
    success: true,
    metadata: { conversation_id: conversationId, resolution: resolutionRaw },
  });
  logInfo(
    `[Guru] post-call ${conversationId} processed (ticket ${ticket.reference})`,
  );
}
