import crypto from "crypto";
import fs from "fs";
import path from "path";
import ExcelJS from "exceljs";
import multer from "multer";
import { HttpError } from "../../middleware/errorHandler";
import { prisma } from "../prisma";
import { uploadRoot } from "../upload";

// Chat attachments. Deliberately NOT under the public /uploads folder: these are only
// ever read back by the assistant, for the user who uploaded them.
export const assistantFileRoot = path.resolve(process.cwd(), "private-uploads", "assistant");
fs.mkdirSync(assistantFileRoot, { recursive: true });

export const MAX_ASSISTANT_FILE_BYTES = 30 * 1024 * 1024;
const MAX_STORED_CHARS = 120_000;

type Kind = "image" | "spreadsheet" | "pdf" | "document" | "text";

const TYPES: { ext: string[]; kind: Kind }[] = [
  { ext: [".jpg", ".jpeg", ".png", ".webp", ".gif"], kind: "image" },
  { ext: [".xlsx", ".csv"], kind: "spreadsheet" },
  { ext: [".pdf"], kind: "pdf" },
  { ext: [".docx"], kind: "document" },
  { ext: [".txt", ".md", ".json", ".log", ".xml", ".html", ".htm", ".eml"], kind: "text" },
];
const PUBLISHABLE_EXTENSIONS = [".jpg", ".jpeg", ".png", ".webp", ".gif", ".xlsx", ".csv", ".pdf", ".docx", ".txt", ".md", ".log", ".json"];
const IMAGE_MIME: Record<string, string> = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp", ".gif": "image/gif" };

function kindFor(filename: string): Kind | null {
  const ext = path.extname(filename).toLowerCase();
  return TYPES.find((t) => t.ext.includes(ext))?.kind ?? null;
}

export const assistantUpload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: MAX_ASSISTANT_FILE_BYTES, files: 1 },
  fileFilter: (_req, file, cb) => {
    if (kindFor(file.originalname)) return cb(null, true);
    cb(new HttpError(400, "Unsupported file type. Use images, Excel (.xlsx), CSV, PDF, Word (.docx) or text files."));
  },
});

function cellText(value: ExcelJS.CellValue): string {
  if (value === null || value === undefined) return "";
  if (value instanceof Date) return value.toISOString().slice(0, 10);
  if (typeof value === "object") {
    if ("richText" in value) return value.richText.map((t) => t.text).join("");
    if ("text" in value && typeof value.text === "string") return value.text;
    if ("result" in value) return cellText(value.result as ExcelJS.CellValue);
    if ("error" in value) return "";
  }
  return String(value).replace(/\s+/g, " ").trim();
}

async function extractSpreadsheet(buffer: Buffer, filename: string): Promise<string> {
  if (filename.toLowerCase().endsWith(".csv")) return buffer.toString("utf8").replace(/^﻿/, "");
  const wb = new ExcelJS.Workbook();
  try {
    await wb.xlsx.load(buffer as never);
  } catch {
    throw new HttpError(400, "Couldn't read this Excel file. Save it as .xlsx and try again.");
  }
  const parts: string[] = [];
  for (const ws of wb.worksheets.slice(0, 6)) {
    parts.push(`## Sheet: ${ws.name}`);
    let rows = 0;
    ws.eachRow({ includeEmpty: false }, (row) => {
      if (rows >= 500) return;
      const cells: string[] = [];
      for (let c = 1; c <= Math.min(row.cellCount, 40); c++) cells.push(cellText(row.getCell(c).value));
      if (cells.some(Boolean)) {
        parts.push(`${row.number}: ${cells.join(" | ")}`);
        rows += 1;
      }
    });
    if (ws.actualRowCount > 500) parts.push(`(… ${ws.actualRowCount - 500} more rows not shown)`);
  }
  return parts.join("\n");
}

async function extractPdf(buffer: Buffer): Promise<string> {
  // The package's index.js runs a self-test when loaded without a parent module;
  // requiring the implementation file directly avoids that.
  // eslint-disable-next-line @typescript-eslint/no-require-imports
  const pdfParse = require("pdf-parse/lib/pdf-parse.js") as (b: Buffer) => Promise<{ text: string; numpages: number }>;
  try {
    const result = await pdfParse(buffer);
    const text = result.text.replace(/\n{3,}/g, "\n\n").trim();
    if (!text) throw new HttpError(400, "This PDF has no readable text (it may be a scan). Upload it as an image instead.");
    return `(${result.numpages} page PDF)\n${text}`;
  } catch (err) {
    if (err instanceof HttpError) throw err;
    throw new HttpError(400, "Couldn't read this PDF.");
  }
}

async function extractDocx(buffer: Buffer): Promise<string> {
  // eslint-disable-next-line @typescript-eslint/no-require-imports
  const mammoth = require("mammoth") as { extractRawText: (i: { buffer: Buffer }) => Promise<{ value: string }> };
  try {
    return (await mammoth.extractRawText({ buffer })).value.replace(/\n{3,}/g, "\n\n").trim();
  } catch {
    throw new HttpError(400, "Couldn't read this Word document. Save it as .docx and try again.");
  }
}

function extractText(buffer: Buffer, filename: string): string {
  const text = buffer.toString("utf8").replace(/^﻿/, "");
  if (/\.html?$/i.test(filename)) {
    return text
      .replace(/<(script|style)[\s\S]*?<\/\1>/gi, " ")
      .replace(/<[^>]+>/g, " ")
      .replace(/&nbsp;/g, " ")
      .replace(/[ \t]+/g, " ")
      .replace(/\n\s*\n+/g, "\n")
      .trim();
  }
  return text;
}

export async function saveAssistantFile(userId: string, file: Express.Multer.File) {
  const kind = kindFor(file.originalname);
  if (!kind) throw new HttpError(400, "Unsupported file type");
  const ext = path.extname(file.originalname).toLowerCase();

  let extractedText: string | null = null;
  if (kind === "spreadsheet") extractedText = await extractSpreadsheet(file.buffer, file.originalname);
  else if (kind === "pdf") extractedText = await extractPdf(file.buffer);
  else if (kind === "document") extractedText = await extractDocx(file.buffer);
  else if (kind === "text") extractedText = extractText(file.buffer, file.originalname);
  if (extractedText !== null && extractedText.length > MAX_STORED_CHARS) {
    extractedText = `${extractedText.slice(0, MAX_STORED_CHARS)}\n(… file truncated)`;
  }
  if (kind !== "image" && !extractedText?.trim()) throw new HttpError(400, "This file looks empty.");

  const storedName = `${Date.now()}-${crypto.randomBytes(8).toString("hex")}${ext}`;
  await fs.promises.writeFile(path.join(assistantFileRoot, storedName), file.buffer);
  return prisma.assistantFile.create({
    data: {
      userId,
      filename: file.originalname.slice(0, 255),
      mimeType: kind === "image" ? IMAGE_MIME[ext] : file.mimetype,
      sizeBytes: file.size,
      storedName,
      kind,
      extractedText,
    },
    select: { id: true, filename: true, mimeType: true, sizeBytes: true, kind: true, createdAt: true },
  });
}

/** Only ever the caller's own files. */
export async function loadOwnFiles(userId: string, fileIds: string[]) {
  if (fileIds.length === 0) return [];
  return prisma.assistantFile.findMany({ where: { userId, id: { in: fileIds } } });
}

export async function readFileBuffer(storedName: string) {
  return fs.promises.readFile(path.join(assistantFileRoot, path.basename(storedName)));
}

/** Copies a chat file into the public attachments folder so it can be attached to a card. */
export async function publishAsAttachment(file: { storedName: string; filename: string; mimeType: string; sizeBytes: number }) {
  const ext = path.extname(file.storedName).toLowerCase();
  // Markup files could run script if opened from the public /uploads folder.
  if (PUBLISHABLE_EXTENSIONS.indexOf(ext) === -1) throw new HttpError(400, `"${file.filename}" can't be attached to a card`);
  const name = `${Date.now()}-${crypto.randomInt(1e9)}${ext}`;
  await fs.promises.copyFile(path.join(assistantFileRoot, path.basename(file.storedName)), path.join(uploadRoot, "attachments", name));
  return { url: `/uploads/attachments/${name}`, filename: file.filename, mimeType: file.mimeType, sizeBytes: file.sizeBytes };
}
