import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const outputPath = path.join(__dirname, "大本营答疑资产库_飞书导入模板.xlsx");

const workbook = Workbook.create();

const sheets = [
  {
    name: "答疑场次",
    tableName: "SessionTable",
    headers: [
      "场次编号",
      "标题",
      "日期",
      "答疑老师",
      "飞书资料链接",
      "转写稿",
      "处理状态",
      "原始问答数",
      "标准问答数",
      "高风险数",
      "最近同步时间",
    ],
    sample: [
      "SESSION-2026-07-01",
      "2026年7月1日-大本营答疑分享交流",
      new Date("2026-07-01T00:00:00"),
      "静静",
      "https://zcn7hk6n047c.feishu.cn/file/KOxYbadHVox0oKxLfwUcLwfXnPd",
      "这里粘贴或同步逐字稿正文；后台会优先读取这一列。",
      "待处理",
      0,
      0,
      0,
      new Date("2026-07-04T00:00:00"),
    ],
  },
  {
    name: "原始问答",
    tableName: "RawQATable",
    headers: [
      "场次编号",
      "问题",
      "回答",
      "答疑老师",
      "标签",
      "风险等级",
      "证据片段",
      "审核状态",
      "入库状态",
      "创建时间",
    ],
    sample: [
      "SESSION-2026-07-01",
      "示例问题：孩子写作业拖拉怎么办？",
      "示例回答：先区分能力问题和情绪问题，再设计低阻力启动动作。",
      "静静",
      "亲子沟通, 学习习惯",
      "低",
      "逐字稿中的对应原文片段。",
      "待审核",
      "未入库",
      new Date("2026-07-04T00:00:00"),
    ],
  },
  {
    name: "标准问答",
    tableName: "StandardQATable",
    headers: [
      "标准问题",
      "标准答案",
      "适用人群",
      "标签",
      "风险等级",
      "来源场次",
      "来源问题",
      "状态",
      "是否可调用",
      "创建时间",
    ],
    sample: [
      "孩子写作业拖拉怎么办？",
      "先观察拖拉背后的阻力来源，再把任务拆到可以立刻开始的一小步。",
      "家长",
      "亲子沟通, 学习习惯",
      "低",
      "SESSION-2026-07-01",
      "示例问题：孩子写作业拖拉怎么办？",
      "已审核",
      "是",
      new Date("2026-07-04T00:00:00"),
    ],
  },
];

for (const spec of sheets) {
  const sheet = workbook.worksheets.add(spec.name);
  const colCount = spec.headers.length;
  const range = sheet.getRangeByIndexes(0, 0, 2, colCount);
  range.values = [spec.headers, spec.sample];
  range.format = {
    font: { name: "Microsoft YaHei", size: 10 },
    borders: { preset: "all", style: "thin", color: "#D7DEE8" },
    wrapText: true,
  };
  sheet.getRangeByIndexes(0, 0, 1, colCount).format = {
    fill: "#155E75",
    font: { bold: true, color: "#FFFFFF", name: "Microsoft YaHei" },
  };
  sheet.freezePanes.freezeRows(1);
  sheet.showGridLines = false;
  sheet.tables.add(sheet.getRangeByIndexes(0, 0, 2, colCount), true, spec.tableName);

  for (let i = 0; i < colCount; i += 1) {
    const column = sheet.getRangeByIndexes(0, i, 2, 1);
    column.format.columnWidth = Math.min(32, Math.max(14, spec.headers[i].length * 2 + 8));
  }
  if (spec.name === "答疑场次") {
    sheet.getRange("C2").setNumberFormat("yyyy-mm-dd");
    sheet.getRange("H2:J2").setNumberFormat("#,##0");
    sheet.getRange("K2").setNumberFormat("yyyy-mm-dd");
  }
  if (spec.name === "原始问答") {
    sheet.getRange("J2").setNumberFormat("yyyy-mm-dd");
  }
  if (spec.name === "标准问答") {
    sheet.getRange("J2").setNumberFormat("yyyy-mm-dd");
  }
}

const overview = workbook.worksheets.add("导入说明");
overview.getRange("A1:D1").merge();
overview.getRange("A1").values = [["大本营答疑资产库 - 飞书多维表格导入模板"]];
overview.getRange("A1").format = {
  fill: "#0F766E",
  font: { bold: true, color: "#FFFFFF", size: 14, name: "Microsoft YaHei" },
};
overview.getRange("A3:D7").values = [
  ["工作表", "用途", "后台写入方向", "说明"],
  ["答疑场次", "每一期答疑资料和处理状态", "飞书 -> 后台，并回写状态", "转写稿列可直接放全文；飞书资料链接可放文档链接。"],
  ["原始问答", "AI 从逐字稿提炼出的原始问答", "后台 -> 飞书", "审核前的问答资产池。"],
  ["标准问答", "审核通过后的可调用问答", "后台 -> 飞书", "勾选是否可调用后进入调用库。"],
  ["配置", "后台需要 app_token 和 3 个 table_id", "环境变量", "密钥只放 .env，不写入仓库或数据库。"],
];
overview.getRange("A3:D3").format = {
  fill: "#155E75",
  font: { bold: true, color: "#FFFFFF", name: "Microsoft YaHei" },
};
overview.getRange("A3:D7").format = {
  borders: { preset: "all", style: "thin", color: "#D7DEE8" },
  wrapText: true,
  font: { name: "Microsoft YaHei", size: 10 },
};
overview.getRange("A:D").format.columnWidth = 24;
overview.freezePanes.freezeRows(3);
overview.showGridLines = false;

const errors = await workbook.inspect({
  kind: "match",
  searchTerm: "#REF!|#DIV/0!|#VALUE!|#NAME\\?|#N/A",
  options: { useRegex: true, maxResults: 50 },
  summary: "final formula error scan",
});
console.log(errors.ndjson);

for (const sheetName of ["答疑场次", "原始问答", "标准问答", "导入说明"]) {
  const preview = await workbook.render({
    sheetName,
    autoCrop: "all",
    scale: 1,
    format: "png",
  });
  await fs.writeFile(
    path.join(__dirname, `${sheetName}.png`),
    new Uint8Array(await preview.arrayBuffer()),
  );
}

await fs.mkdir(__dirname, { recursive: true });
const output = await SpreadsheetFile.exportXlsx(workbook);
await output.save(outputPath);
console.log(outputPath);
