import { Hono } from "hono";
import type { Context } from "hono";
import { createMiddleware } from "hono/factory";
import * as crypto from "node:crypto";
import { env } from "@/lib/env";
import { logError, logInfo } from "@/lib/logger";
import { safeEqual } from "@/middlewares/apiKeyAuth";
import { rateLimit } from "@/middlewares/rate-limit";
import { getKevoPostCallQueue } from "@/internal/queue/kevo-postcall.queue";
import { getGuruPostCallQueue } from "@/internal/queue/guru-postcall.queue";
import type { RepositoryContext } from "@/internal/datastore/repository";
import { KevoRepository } from "@/internal/kevo/kevo.repository";
import { KevoServices } from "@/internal/kevo/kevo.service";
import { FlagIssueSchema } from "@/internal/kevo/kevo.schema";

/**
 * Public (non-console-session) Kevo endpoints, mounted at /v1/kevo.
 * Called by ElevenLabs, not by the admin console:
 *   POST /tools/flag-issue   — the agent's flag_issue server tool
 *   POST /webhooks/post-call — post-call webhook (added in the webhook phase)
 *
 * These paths are excluded from the activity-log middleware: payloads carry
 * member conversation text, which must not land in admin_activity_log.
 */
export const KevoPublicRoutes = new Hono();

/** Shared-secret header check for the server tool (timing-safe). */
const kevoToolAuth = () =>
  createMiddleware(async (c, next) => {
    const secret = env.GetString("KEVO_TOOL_SHARED_SECRET");
    if (!secret) {
      logError("[Kevo] KEVO_TOOL_SHARED_SECRET is not set");
      return c.text("Server configuration error", 500);
    }
    const provided = c.req.header("x-kevo-secret");
    if (!provided || !safeEqual(provided.trim(), secret)) {
      return c.text("Unauthorized", 401);
    }
    await next();
  });

KevoPublicRoutes.post(
  "/tools/flag-issue",
  kevoToolAuth(),
  rateLimit("kevo", 60, 60),
  async (c: Context) => {
    // The response body is read aloud by the agent — keep it small and fast,
    // and never use the console's {success,data} envelope here.
    let body: unknown;
    try {
      body = await c.req.json();
    } catch {
      return c.json({ status: "error", message: "Invalid JSON body" }, 400);
    }

    const parsed = FlagIssueSchema.safeParse(body);
    if (!parsed.success) {
      return c.json(
        {
          status: "error",
          message: parsed.error.issues
            .map((i) => `${i.path.join(".")}: ${i.message}`)
            .join(", "),
        },
        400,
      );
    }

    try {
      const services = KevoServices({
        KevoRepository: KevoRepository(c as RepositoryContext),
      });
      const { flag } = await services.createFlag(parsed.data, "IN_CALL");
      return c.json({ status: "flagged", reference: flag.reference });
    } catch (err) {
      logError(`[Kevo] flag-issue failed: ${err}`);
      return c.json(
        { status: "error", message: "Could not record the flag" },
        500,
      );
    }
  },
);

/**
 * ElevenLabs post-call webhook (docs/kevo-flagging/API_NOTES.md §4).
 * Signature: `ElevenLabs-Signature: t=<unix>,v0=<hex>` where v0 is
 * HMAC-SHA256 over "{t}.{raw_body}". Stale (>30 min) timestamps rejected.
 * Responds 200 fast; processing happens in the kevo-postcall BullMQ job.
 */
const WEBHOOK_TOLERANCE_SECS = 30 * 60;

export const verifyElevenLabsSignature = (
  rawBody: string,
  header: string,
  secret: string,
  nowSecs = Math.floor(Date.now() / 1000),
): boolean => {
  const parts = Object.fromEntries(
    header.split(",").map((p) => p.split("=", 2) as [string, string]),
  );
  const t = Number(parts.t);
  const v0 = parts.v0;
  if (!Number.isFinite(t) || !v0) return false;
  if (Math.abs(nowSecs - t) > WEBHOOK_TOLERANCE_SECS) return false;
  const expected = crypto
    .createHmac("sha256", secret)
    .update(`${t}.${rawBody}`)
    .digest("hex");
  return safeEqual(v0, expected);
};

KevoPublicRoutes.post("/webhooks/post-call", async (c: Context) => {
  const secret = env.GetString("ELEVENLABS_WEBHOOK_SECRET");
  if (!secret) {
    logError("[Kevo] ELEVENLABS_WEBHOOK_SECRET is not set");
    return c.text("Server configuration error", 500);
  }

  const sigHeader = c.req.header("elevenlabs-signature");
  if (!sigHeader) {
    logError("[Kevo] post-call webhook rejected: missing signature header");
    return c.text("Missing signature", 401);
  }

  const rawBody = await c.req.text();
  if (!verifyElevenLabsSignature(rawBody, sigHeader, secret)) {
    logError(
      "[Kevo] post-call webhook rejected: invalid signature (check ELEVENLABS_WEBHOOK_SECRET matches the dashboard webhook)",
    );
    return c.text("Invalid signature", 401);
  }

  let event: {
    type?: string;
    data?: { conversation_id?: string; agent_id?: string };
  };
  try {
    event = JSON.parse(rawBody);
  } catch {
    return c.text("Invalid JSON", 400);
  }

  // Only transcription events matter here; ack everything else so
  // ElevenLabs doesn't retry or auto-disable the webhook.
  if (event.type !== "post_call_transcription") {
    return c.json({ received: true });
  }
  const conversationId = event.data?.conversation_id;
  if (!conversationId) return c.text("Missing conversation_id", 400);
  logInfo(
    `[Kevo] post-call webhook received: ${conversationId} (agent ${event.data?.agent_id ?? "unknown"})`,
  );

  // The post-call webhook is WORKSPACE-wide: every agent's calls land here.
  // Route by agent id so a second agent (Subito AI Guru) never creates Kevo
  // flags. Guru events go to the guru-postcall queue; unknown agents are
  // acked and ignored.
  const agentId = event.data?.agent_id;
  const kevoAgentId = process.env.ELEVENLABS_AGENT_ID;
  const guruAgentId = process.env.SUBITO_AI_GURU_ELEVENLABS_AGENT_ID;
  if (agentId && kevoAgentId && agentId !== kevoAgentId) {
    if (agentId === guruAgentId) {
      try {
        await getGuruPostCallQueue().add(
          "post-call",
          { conversationId },
          { jobId: `guru-postcall-${conversationId}` },
        );
      } catch (err) {
        logError(`[Guru] failed to enqueue post-call job: ${err}`);
        return c.text("Queue unavailable", 503); // 5xx → ElevenLabs retries
      }
    } else {
      logError(`[Kevo] post-call from unknown agent ${agentId} ignored`);
    }
    return c.json({ received: true });
  }

  try {
    // jobId makes webhook retries idempotent: same conversation, same job.
    await getKevoPostCallQueue().add(
      "post-call",
      { conversationId },
      { jobId: `postcall-${conversationId}` },
    );
  } catch (err) {
    logError(`[Kevo] failed to enqueue post-call job: ${err}`);
    return c.text("Queue unavailable", 503); // 5xx → ElevenLabs retries
  }
  return c.json({ received: true });
});
