import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import * as XLSX from "xlsx";
import type { PriceComparisonExportRequest, PriceComparisonExportResult, PriceComparisonRow } from "../../shared/types";

const COLUMNS = [
  "平台",
  "商品/规格",
  "价格",
  "折算单价",
  "状态",
  "来源",
  "备注",
  "依据",
  "链接"
];

export async function exportPriceComparisonWorkbook(
  request: PriceComparisonExportRequest,
  outputDir: string
): Promise<PriceComparisonExportResult> {
  const rows = request.rows.map(normalizeRow).filter((row) => row.platform || row.productName || row.price);
  if (rows.length === 0) {
    throw new Error("没有可导出的价格对比数据");
  }

  await mkdir(outputDir, { recursive: true });
  const createdAt = new Date();
  const fileName = `${sanitizeFileName(request.title || inferTitle(rows))}_${formatTimestamp(createdAt)}.xlsx`;
  const filePath = path.join(outputDir, fileName);

  const workbook = XLSX.utils.book_new();
  const data = [
    COLUMNS,
    ...rows.map((row) => [
      safeExcelText(row.platform),
      safeExcelText(row.productName),
      safeExcelText(row.price),
      safeExcelText(row.unitPrice || ""),
      safeExcelText(row.status),
      safeExcelText(row.source),
      safeExcelText(row.note),
      safeExcelText(row.evidence || ""),
      safeExcelText(row.sourceUrl || "")
    ])
  ];

  const sheet = XLSX.utils.aoa_to_sheet(data);
  sheet["!cols"] = [
    { wch: 12 },
    { wch: 32 },
    { wch: 14 },
    { wch: 14 },
    { wch: 14 },
    { wch: 20 },
    { wch: 38 },
    { wch: 58 },
    { wch: 48 }
  ];
  sheet["!autofilter"] = { ref: XLSX.utils.encode_range({ s: { r: 0, c: 0 }, e: { r: data.length - 1, c: COLUMNS.length - 1 } }) };
  XLSX.utils.book_append_sheet(workbook, sheet, "价格对比");

  const metaSheet = XLSX.utils.aoa_to_sheet([
    ["导出标题", request.title || inferTitle(rows)],
    ["导出时间", createdAt.toLocaleString("zh-CN", { hour12: false })],
    ["数据行数", rows.length],
    ["说明", "外部平台价格来自公开页面、搜索结果或授权接口线索，受登录、风控、地区、券、会员价、运费和活动影响，仅作运营参考。"]
  ]);
  metaSheet["!cols"] = [{ wch: 16 }, { wch: 92 }];
  XLSX.utils.book_append_sheet(workbook, metaSheet, "说明");

  const buffer = XLSX.write(workbook, { type: "buffer", bookType: "xlsx" }) as Buffer;
  await writeFile(filePath, buffer);

  return {
    filePath,
    fileName,
    rowCount: rows.length,
    createdAt: createdAt.toISOString()
  };
}

function normalizeRow(row: PriceComparisonRow): PriceComparisonRow {
  return {
    platform: String(row.platform ?? ""),
    productName: String(row.productName ?? ""),
    price: String(row.price ?? ""),
    unitPrice: row.unitPrice ? String(row.unitPrice) : undefined,
    status: String(row.status ?? ""),
    source: String(row.source ?? ""),
    note: String(row.note ?? ""),
    sourceUrl: row.sourceUrl ? String(row.sourceUrl) : undefined,
    evidence: row.evidence ? String(row.evidence) : undefined
  };
}

function inferTitle(rows: PriceComparisonRow[]): string {
  const systemRow = rows.find((row) => row.platform === "smqjh系统") ?? rows[0];
  const keyword = systemRow.productName || "商品价格对比";
  return `商品价格对比_${keyword}`;
}

function sanitizeFileName(value: string): string {
  const cleaned = value
    .replace(/[<>:"/\\|?*\x00-\x1F]/g, " ")
    .replace(/\s+/g, " ")
    .trim()
    .slice(0, 80);
  return cleaned || "商品价格对比";
}

function formatTimestamp(value: Date): string {
  const pad = (item: number) => String(item).padStart(2, "0");
  return [
    value.getFullYear(),
    pad(value.getMonth() + 1),
    pad(value.getDate()),
    "_",
    pad(value.getHours()),
    pad(value.getMinutes()),
    pad(value.getSeconds())
  ].join("");
}

function safeExcelText(value: string): string {
  const text = String(value ?? "");
  return /^[=+\-@]/.test(text) ? `'${text}` : text;
}
