import type { Context } from "hono";
import { error, success } from "@/lib/response";
import type { RepositoryContext } from "@/internal/datastore/repository";
import { GuruRepository } from "@/internal/guru/guru.repository";
import { GuruServices } from "@/internal/guru/guru.service";
import {
  AllowlistAddSchema,
  BindConversationSchema,
  CreateTicketSchema,
  ListAuditSchema,
  ListTicketsSchema,
} from "@/internal/guru/guru.schema";
import { elevenLabsRequest } from "@/lib/elevenlabs/client";
import { logError } from "@/lib/logger";
import {
  confirmAction,
  declineAction,
  toActionDTO,
} from "@/internal/guru/guru-actions.service";
import { EDIT_REFUSAL_MESSAGE } from "@/internal/guru/guru.service";

const repoFor = (c: Context) => GuruRepository(c as RepositoryContext);
const servicesFor = (c: Context) =>
  GuruServices({ GuruRepository: GuruRepository(c as RepositoryContext) });
const actorOf = (c: Context) => ({
  id: c.get("consoleUserId") as string,
  email: (c.get("adminEmail") as string) ?? "unknown",
});

const parseJson = async (c: Context): Promise<unknown | null> => {
  try {
    return await c.req.json();
  } catch {
    return null;
  }
};

// ---- tickets ----

export const createTicketHandler = async (c: Context) => {
  const parsed = CreateTicketSchema.safeParse((await parseJson(c)) ?? {});
  if (!parsed.success)
    return error(c, parsed.error.issues.map((i) => i.message).join(", "), 400);
  const ticket = await servicesFor(c).createTicket(parsed.data, actorOf(c));
  return success(c, { ticket });
};

/** Own tickets only (guru.read) — owner id comes from the session, never the body. */
export const listMyTicketsHandler = async (c: Context) => {
  const parsed = ListTicketsSchema.safeParse((await parseJson(c)) ?? {});
  if (!parsed.success)
    return error(c, parsed.error.issues.map((i) => i.message).join(", "), 400);
  const { tickets, total } = await repoFor(c).listTickets({
    ...parsed.data,
    console_user_id: actorOf(c).id,
  });
  return success(c, {
    tickets,
    total,
    page: parsed.data.page,
    limit: parsed.data.limit,
  });
};

/** All tickets (guru-admin.read). */
export const listAllTicketsHandler = async (c: Context) => {
  const parsed = ListTicketsSchema.safeParse((await parseJson(c)) ?? {});
  if (!parsed.success)
    return error(c, parsed.error.issues.map((i) => i.message).join(", "), 400);
  const { tickets, total } = await repoFor(c).listTickets(parsed.data);
  return success(c, {
    tickets,
    total,
    page: parsed.data.page,
    limit: parsed.data.limit,
  });
};

/**
 * Ticket detail for the owner (guru.read). Not-owned tickets return 404 —
 * existence of other concierges' tickets is not leaked. Admins use the
 * /admin variant below.
 */
export const getMyTicketHandler = async (c: Context) => {
  const repo = repoFor(c);
  const ticket = await repo.getTicketByReference(c.req.param("reference") ?? "");
  if (!ticket || ticket.console_user_id !== actorOf(c).id)
    return error(c, "Ticket not found", 404);
  const actions = await repo.listActionsForTicket(ticket.id);
  return success(c, { ticket, actions: actions.map(toActionDTO) });
};

/** Ticket detail without the ownership restriction (guru-admin.read). */
export const getAnyTicketHandler = async (c: Context) => {
  const repo = repoFor(c);
  const ticket = await repo.getTicketByReference(c.req.param("reference") ?? "");
  if (!ticket) return error(c, "Ticket not found", 404);
  const actions = await repo.listActionsForTicket(ticket.id);
  return success(c, { ticket, actions: actions.map(toActionDTO) });
};

/** Analytics (guru-admin.read): volume, outcomes, time to resolve. */
export const analyticsHandler = async (c: Context) =>
  success(c, await repoFor(c).ticketStats());

// ---- pending actions (the confirmation gate, spec §3) ----

/** The chat polls this for new confirmation cards. Owner only. */
export const listTicketActionsHandler = async (c: Context) => {
  const ticket = await ownedTicketOr404(c);
  if (!ticket) return error(c, "Ticket not found", 404);
  const actions = await repoFor(c).listActionsForTicket(ticket.id);
  return success(c, { actions: actions.map(toActionDTO) });
};

export const confirmActionHandler = async (c: Context) => {
  const outcome = await confirmAction(
    c,
    c.req.param("id") ?? "",
    actorOf(c),
  );
  switch (outcome.kind) {
    case "not_found":
      return error(c, "Action not found", 404);
    case "already_handled":
      return error(c, "This action was already handled.", 409);
    case "expired":
      return error(c, "This action expired. Ask the Guru to propose it again.", 410);
    case "refused":
      return error(c, EDIT_REFUSAL_MESSAGE, 403);
    case "failed":
      return error(c, outcome.error, 502);
    case "executed":
      return success(c, { executed: true, ...(outcome.display ?? {}) });
  }
};

export const declineActionHandler = async (c: Context) => {
  const result = await declineAction(c, c.req.param("id") ?? "", actorOf(c));
  if (result === "not_found") return error(c, "Action not found", 404);
  if (result === "already_handled")
    return error(c, "This action was already handled.", 409);
  return success(c, { declined: true });
};

// ---- chat sessions ----

/** Owner-only ticket fetch shared by the session/bind handlers. */
const ownedTicketOr404 = async (c: Context) => {
  const ticket = await repoFor(c).getTicketByReference(
    c.req.param("reference") ?? "",
  );
  if (!ticket || ticket.console_user_id !== actorOf(c).id) return null;
  return ticket;
};

/**
 * Mint an ElevenLabs signed URL for the Guru agent (text chat). The API key
 * never reaches the client; the signed URL is short-lived and single-use.
 */
export const startSessionHandler = async (c: Context) => {
  const ticket = await ownedTicketOr404(c);
  if (!ticket) return error(c, "Ticket not found", 404);

  const agentId = process.env.SUBITO_AI_GURU_ELEVENLABS_AGENT_ID;
  if (!agentId) {
    logError("[Guru] SUBITO_AI_GURU_ELEVENLABS_AGENT_ID is not set");
    return error(c, "The Guru agent is not configured yet", 503);
  }

  try {
    const { signed_url } = await elevenLabsRequest<{ signed_url: string }>(
      `/v1/convai/conversation/get-signed-url?agent_id=${encodeURIComponent(agentId)}`,
      { signal: AbortSignal.timeout(10_000) },
    );
    // Server-verified context for the agent prompt's {{dynamic_variables}}.
    // Informational only — writes are still gated by the confirm endpoint.
    const actor = actorOf(c);
    const { ConsoleUserRepository } = await import(
      "@/internal/console-users/console-users.repository"
    );
    const user = await ConsoleUserRepository(
      c as RepositoryContext,
    ).FindEntryByEmailOrUsername(actor.email);
    const dynamic_variables = {
      concierge_name: user?.first_name ?? actor.email.split("@")[0],
      concierge_email: actor.email,
      service_center_name:
        (user as { service_center?: string | null } | undefined)
          ?.service_center ?? "Karma Concierge",
      can_edit: String(await repoFor(c).isAllowlisted(actor.email)),
      ticket_id: ticket.reference,
    };
    return success(c, {
      signed_url,
      reference: ticket.reference,
      dynamic_variables,
    });
  } catch (err) {
    logError(`[Guru] signed-url mint failed: ${err}`);
    return error(c, "Could not start a chat session. Try again.", 502);
  }
};

/**
 * Bind the ElevenLabs conversation id to the caller's own ticket. A client
 * can only bind a conversation to a ticket it owns, so the mapping that
 * later authorizes tool calls (conversation → concierge) is trustworthy.
 * Binding to a closed ticket reopens it.
 */
export const bindConversationHandler = async (c: Context) => {
  const parsed = BindConversationSchema.safeParse(await parseJson(c));
  if (!parsed.success) return error(c, "conversation_id is required", 400);

  const repo = repoFor(c);
  const ticket = await ownedTicketOr404(c);
  if (!ticket) return error(c, "Ticket not found", 404);

  // A conversation belongs to exactly one ticket.
  const existing = await repo.getTicketByConversation(
    parsed.data.conversation_id,
  );
  if (existing && existing.id !== ticket.id)
    return error(c, "That conversation belongs to another ticket", 409);

  await repo.appendConversation(ticket.id, parsed.data.conversation_id);
  const reopened = ticket.status !== "OPEN";
  if (reopened) {
    await repo.updateTicket(ticket.id, {
      status: "OPEN",
      resolution: null,
      resolved_at: null,
    });
  }
  await repo.insertAudit({
    ticket_id: ticket.id,
    action: reopened ? "ticket.reopened" : "ticket.conversation_bound",
    actor_email: actorOf(c).email,
    member_ref: ticket.member_ref,
    metadata: { conversation_id: parsed.data.conversation_id },
  });
  return success(c, { bound: true, reopened });
};

// ---- screenshots (meeting notes §2/§4: attached to the ClickUp task) ----

const ATTACHMENT_TYPES = new Set([
  "image/png",
  "image/jpeg",
  "image/webp",
  "image/gif",
  "application/pdf",
]);
const ATTACHMENT_MAX_BYTES = 8 * 1024 * 1024;

export const addAttachmentHandler = async (c: Context) => {
  const ticket = await ownedTicketOr404(c);
  if (!ticket) return error(c, "Ticket not found", 404);

  let file: File | undefined;
  try {
    const body = await c.req.parseBody();
    const candidate = body.file ?? body.attachment;
    if (candidate instanceof File) file = candidate;
  } catch {
    /* fall through to validation error */
  }
  if (!file) return error(c, "Attach a file in the 'file' field", 400);
  if (!ATTACHMENT_TYPES.has(file.type))
    return error(c, "Only PNG, JPEG, WEBP, GIF or PDF screenshots are allowed", 415);
  if (file.size > ATTACHMENT_MAX_BYTES)
    return error(c, "Attachments are limited to 8 MB", 413);

  try {
    const { ensureClickUpTaskForTicket } = await import(
      "@/internal/guru/guru-lifecycle.service"
    );
    const { uploadClickUpTaskAttachment } = await import(
      "@/lib/clickup/client"
    );
    const repo = repoFor(c);
    const taskId = await ensureClickUpTaskForTicket(
      repo,
      ticket,
      actorOf(c).email,
    );
    if (!taskId)
      return error(
        c,
        "Screenshots need the ClickUp list to be configured (GURU_CLICKUP_LIST_ID).",
        503,
      );
    const uploaded = await uploadClickUpTaskAttachment(taskId, {
      name: file.name || "screenshot.png",
      type: file.type,
      bytes: await file.arrayBuffer(),
    });
    await repo.insertAudit({
      ticket_id: ticket.id,
      action: "ticket.attachment_added",
      actor_email: actorOf(c).email,
      member_ref: ticket.member_ref,
      clickup_task_id: taskId,
      success: true,
      metadata: { name: uploaded.title },
    });
    return success(c, { attached: true, title: uploaded.title });
  } catch (err) {
    logError(`[Guru] attachment upload failed: ${err}`);
    return error(c, "Could not attach the file. Try again.", 502);
  }
};

/** Concierge sign-off: close own ticket, sync ClickUp + Viewpoint. */
export const closeTicketHandler = async (c: Context) => {
  const ticket = await ownedTicketOr404(c);
  if (!ticket) return error(c, "Ticket not found", 404);
  if (ticket.status !== "OPEN")
    return error(c, "This case is already closed.", 409);
  const { closeTicketByConcierge } = await import(
    "@/internal/guru/guru-lifecycle.service"
  );
  await closeTicketByConcierge(repoFor(c), ticket, actorOf(c).email);
  return success(c, { closed: true });
};

// ---- transcripts (fetched from ElevenLabs on demand, never stored; kevo
// transcript-proxy pattern) ----

interface ElevenConversation {
  transcript?: Array<{
    role?: string;
    message?: string | null;
    time_in_call_secs?: number;
  }>;
  metadata?: { start_time_unix_secs?: number };
}

const ticketTranscript = async (
  c: Context,
  ticket: { conversation_ids: string[] },
) => {
  const { redactSensitive } = await import("@/internal/kevo/kevo.service");
  // Last 5 conversations are plenty for a case review.
  const ids = (ticket.conversation_ids ?? []).slice(-5);
  const conversations = await Promise.all(
    ids.map(async (id) => {
      try {
        const detail = await elevenLabsRequest<ElevenConversation>(
          `/v1/convai/conversations/${encodeURIComponent(id)}`,
          { signal: AbortSignal.timeout(10_000) },
        );
        return {
          conversation_id: id,
          started_at: detail.metadata?.start_time_unix_secs
            ? new Date(detail.metadata.start_time_unix_secs * 1000).toISOString()
            : null,
          turns: (detail.transcript ?? [])
            .filter((t) => t.message)
            .map((t) => ({
              role: t.role === "user" ? "user" : "agent",
              text: redactSensitive(t.message as string),
            })),
        };
      } catch (err) {
        logError(`[Guru] transcript fetch failed for ${id}: ${err}`);
        return { conversation_id: id, started_at: null, turns: [], unavailable: true };
      }
    }),
  );
  return success(c, { conversations });
};

export const getMyTicketTranscriptHandler = async (c: Context) => {
  const ticket = await ownedTicketOr404(c);
  if (!ticket) return error(c, "Ticket not found", 404);
  return ticketTranscript(c, ticket);
};

export const getAnyTicketTranscriptHandler = async (c: Context) => {
  const ticket = await repoFor(c).getTicketByReference(
    c.req.param("reference") ?? "",
  );
  if (!ticket) return error(c, "Ticket not found", 404);
  return ticketTranscript(c, ticket);
};

// ---- ClickUp updates (concierges never need ClickUp access — the Console
// shows ticket status and comments; spec §2) ----

const ticketUpdates = async (c: Context, ticket: { clickup_task_id: string | null }) => {
  if (!ticket.clickup_task_id)
    return success(c, { updates: [], task_status: null });
  try {
    const { getClickUpTask, getClickUpTaskComments } = await import(
      "@/lib/clickup/client"
    );
    const { redactSensitive } = await import("@/internal/kevo/kevo.service");
    // Status sync back to Console 2 (meeting notes workstream 5), read-only.
    const [comments, task] = await Promise.all([
      getClickUpTaskComments(ticket.clickup_task_id),
      getClickUpTask(ticket.clickup_task_id).catch(() => null),
    ]);
    return success(c, {
      task_status: task?.status ?? null,
      updates: comments.map((cm) => ({
        at: cm.date ? new Date(Number(cm.date)).toISOString() : null,
        by: cm.user?.username ?? "team",
        text: redactSensitive(cm.comment_text ?? ""),
      })),
    });
  } catch (err) {
    logError(`[Guru] ClickUp updates fetch failed: ${err}`);
    return error(c, "Could not load case updates right now.", 502);
  }
};

export const getMyTicketUpdatesHandler = async (c: Context) => {
  const ticket = await ownedTicketOr404(c);
  if (!ticket) return error(c, "Ticket not found", 404);
  return ticketUpdates(c, ticket);
};

export const getAnyTicketUpdatesHandler = async (c: Context) => {
  const ticket = await repoFor(c).getTicketByReference(
    c.req.param("reference") ?? "",
  );
  if (!ticket) return error(c, "Ticket not found", 404);
  return ticketUpdates(c, ticket);
};

// ---- edit allowlist (super admin only — see route guards) ----

export const listAllowlistHandler = async (c: Context) =>
  success(c, { allowlist: await repoFor(c).listAllowlist() });

export const addAllowlistHandler = async (c: Context) => {
  const parsed = AllowlistAddSchema.safeParse(await parseJson(c));
  if (!parsed.success) return error(c, "A valid email is required", 400);
  const entry = await servicesFor(c).addToAllowlist(
    parsed.data.email,
    actorOf(c).email,
  );
  if (!entry) return error(c, "That email is already on the allowlist", 409);
  return success(c, { entry });
};

export const removeAllowlistHandler = async (c: Context) => {
  const parsed = AllowlistAddSchema.safeParse(await parseJson(c));
  if (!parsed.success) return error(c, "A valid email is required", 400);
  const removed = await servicesFor(c).removeFromAllowlist(
    parsed.data.email,
    actorOf(c).email,
  );
  if (!removed) return error(c, "That email is not on the allowlist", 404);
  return success(c, { removed: true });
};

// ---- audit log (super admin only — see route guards) ----

export const listAuditHandler = async (c: Context) => {
  const parsed = ListAuditSchema.safeParse((await parseJson(c)) ?? {});
  if (!parsed.success)
    return error(c, parsed.error.issues.map((i) => i.message).join(", "), 400);
  const { entries, total } = await repoFor(c).listAudit(parsed.data);
  return success(c, {
    entries,
    total,
    page: parsed.data.page,
    limit: parsed.data.limit,
  });
};
