import { Router } from "express";
import rateLimit from "express-rate-limit";
import multer from "multer";
import { z } from "zod";
import type { AssistantAction } from "@prisma/client";
import { loadScope } from "../lib/assistant/access";
import { cancelAction, confirmAction } from "../lib/assistant/actions";
import { runAssistant } from "../lib/assistant/agent";
import { assistantUpload, loadOwnFiles, saveAssistantFile } from "../lib/assistant/files";
import { getAssistantSettings, getOpenAiSettings, isSupportedAudio, requireOpenAiConfig, transcribeAudio } from "../lib/openai";
import { prisma } from "../lib/prisma";
import { HttpError } from "../middleware/errorHandler";
import { requireAuth } from "../middleware/requireAuth";

export const assistantRouter = Router();
assistantRouter.use(requireAuth);

function perUserLimiter(prefix: string, limit: number, message: string) {
  return rateLimit({
    windowMs: 15 * 60 * 1000,
    limit,
    standardHeaders: true,
    legacyHeaders: false,
    keyGenerator: (req) => `${prefix}:${req.userId}`,
    message: { error: message },
  });
}
const chatLimiter = perUserLimiter("assistant-chat", 60, "You're sending messages very quickly. Please wait a few minutes.");
const fileLimiter = perUserLimiter("assistant-file", 40, "Too many uploads in a short time. Please wait a few minutes.");
const voiceLimiter = perUserLimiter("assistant-voice", 40, "Too many voice messages in a short time. Please wait a few minutes.");

function serializeAction(a: AssistantAction) {
  return { id: a.id, kind: a.kind, status: a.status, preview: a.preview, result: a.result, createdAt: a.createdAt, expiresAt: a.expiresAt };
}

async function ownConversation(userId: string, id: string) {
  const conversation = await prisma.assistantConversation.findFirst({ where: { id, userId } });
  if (!conversation) throw new HttpError(404, "Conversation not found");
  return conversation;
}

async function actionsFor(userId: string, conversationId: string) {
  const actions = await prisma.assistantAction.findMany({ where: { userId, conversationId } });
  return actions.map(serializeAction);
}

async function filesFor(userId: string, ids: string[]) {
  const files = await loadOwnFiles(userId, ids);
  return files.map((f) => ({ id: f.id, filename: f.filename, kind: f.kind, sizeBytes: f.sizeBytes }));
}

assistantRouter.get("/status", async (_req, res, next) => {
  try {
    const [assistant, openai] = await Promise.all([getAssistantSettings(), getOpenAiSettings()]);
    res.json({ enabled: assistant.enabled, configured: !!openai.apiKey });
  } catch (err) {
    next(err);
  }
});

assistantRouter.get("/conversations", async (req, res, next) => {
  try {
    const conversations = await prisma.assistantConversation.findMany({
      where: { userId: req.userId! },
      orderBy: { updatedAt: "desc" },
      take: 30,
      select: { id: true, title: true, updatedAt: true },
    });
    res.json({ conversations });
  } catch (err) {
    next(err);
  }
});

assistantRouter.get("/conversations/:id", async (req, res, next) => {
  try {
    const conversation = await ownConversation(req.userId!, req.params.id);
    const messages = await prisma.assistantMessage.findMany({
      where: { conversationId: conversation.id },
      orderBy: { createdAt: "asc" },
      take: 200,
      select: { id: true, role: true, content: true, blocks: true, fileIds: true, createdAt: true },
    });
    const fileIds = [...new Set(messages.flatMap((m) => (m.fileIds as string[] | null) ?? []))];
    res.json({
      conversation: { id: conversation.id, title: conversation.title },
      messages,
      actions: await actionsFor(req.userId!, conversation.id),
      files: await filesFor(req.userId!, fileIds),
    });
  } catch (err) {
    next(err);
  }
});

const chatSchema = z.object({
  conversationId: z.string().optional(),
  message: z.string().max(8000).default(""),
  fileIds: z.array(z.string()).max(6).default([]),
  path: z.string().max(500).optional(),
});

assistantRouter.post("/chat", chatLimiter, async (req, res, next) => {
  try {
    const data = chatSchema.parse(req.body);
    const text = data.message.trim();
    const files = await loadOwnFiles(req.userId!, data.fileIds);
    if (!text && files.length === 0) throw new HttpError(400, "Type a message or attach a file");

    const conversation = data.conversationId
      ? await ownConversation(req.userId!, data.conversationId)
      : await prisma.assistantConversation.create({
          data: { userId: req.userId!, title: (text || files[0]?.filename || "New chat").slice(0, 60) },
        });

    const userMessage = await prisma.assistantMessage.create({
      data: { conversationId: conversation.id, role: "user", content: text, fileIds: files.map((f) => f.id) },
    });

    let result;
    try {
      const [scope, user] = await Promise.all([
        loadScope(req.userId!),
        prisma.user.findUniqueOrThrow({ where: { id: req.userId! }, select: { name: true, email: true } }),
      ]);
      result = await runAssistant({ scope, user, conversationId: conversation.id, text, files, path: data.path });
    } catch (err) {
      // Keep the history consistent: a question without an answer is dropped.
      await prisma.assistantMessage.delete({ where: { id: userMessage.id } }).catch(() => undefined);
      throw err;
    }

    const assistantMessage = await prisma.assistantMessage.create({
      data: {
        conversationId: conversation.id,
        role: "assistant",
        content: result.text,
        blocks: result.blocks as never,
        contextNote: result.contextNote || null,
      },
    });
    await prisma.assistantConversation.update({ where: { id: conversation.id }, data: { updatedAt: new Date() } });

    res.json({
      conversation: { id: conversation.id, title: conversation.title },
      messages: [userMessage, assistantMessage].map((m) => ({ id: m.id, role: m.role, content: m.content, blocks: m.blocks, fileIds: m.fileIds, createdAt: m.createdAt })),
      actions: await actionsFor(req.userId!, conversation.id),
      files: await filesFor(req.userId!, files.map((f) => f.id)),
    });
  } catch (err) {
    next(err);
  }
});

assistantRouter.post("/files", fileLimiter, assistantUpload.single("file"), async (req, res, next) => {
  try {
    if (!req.file) throw new HttpError(400, "No file uploaded");
    const file = await saveAssistantFile(req.userId!, req.file);
    res.status(201).json({ file });
  } catch (err) {
    next(err);
  }
});

const voiceUpload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 25 * 1024 * 1024, files: 1 },
  fileFilter: (_req, file, cb) => (isSupportedAudio(file.mimetype) ? cb(null, true) : cb(new HttpError(400, "Unsupported audio format"))),
});

assistantRouter.post("/transcribe", voiceLimiter, voiceUpload.single("audio"), async (req, res, next) => {
  try {
    if (!req.file) throw new HttpError(400, "No recording uploaded");
    const settings = await getAssistantSettings();
    if (!settings.enabled) throw new HttpError(403, "The AI assistant is turned off");
    const config = await requireOpenAiConfig();
    const text = await transcribeAudio(config, req.file, "A request to the My Assisto task assistant about boards, tasks, workspaces and deadlines.");
    res.json({ text });
  } catch (err) {
    next(err);
  }
});

assistantRouter.post("/actions/:id/confirm", async (req, res, next) => {
  try {
    const scope = await loadScope(req.userId!);
    const action = await confirmAction(scope, req.params.id);
    res.json({ action: serializeAction(action) });
  } catch (err) {
    next(err);
  }
});

assistantRouter.post("/actions/:id/cancel", async (req, res, next) => {
  try {
    const action = await cancelAction(req.userId!, req.params.id);
    res.json({ action: serializeAction(action) });
  } catch (err) {
    next(err);
  }
});
