import { readFile, writeFile } from "node:fs/promises";
import { resolve } from "node:path";

const [, , inputPath, outputPath] = process.argv;

if (!inputPath || !outputPath) {
  throw new Error("Usage: node scripts/build-feishu-snapshot.mjs <input.json> <output.json>");
}

const payload = JSON.parse(await readFile(resolve(inputPath), "utf8"));
const sheet = payload?.data?.sheets?.[0];

if (!sheet || !Array.isArray(sheet.data)) {
  throw new Error("Invalid lark-cli +table-get payload");
}

const rows = sheet.data
  .map((row, index) => ({
    sourceRow: Number(row[0]) || index + 1,
    title: String(row[2] ?? "").trim(),
    body: String(row[3] ?? "").trim(),
  }))
  .filter((row) => row.title);

const snapshot = {
  wikiToken: "BSzxwRbGJi5dWoksauicUjtonks",
  sheetId: "954953",
  sheetName: sheet.name,
  sourceRange: sheet.range,
  syncedAt: new Date().toISOString(),
  columns: [
    "序号（不能改）",
    "标题",
    "笔记内容（正文+话题）",
    "图片1",
    "图片2",
    "图片3",
  ],
  rows,
};

await writeFile(resolve(outputPath), `${JSON.stringify(snapshot, null, 2)}\n`, "utf8");
console.log(`Wrote ${rows.length} rows to ${outputPath}`);
