import { fetchReadwiseList } from "https://esm.town/v/ofalvai/fetchReadwiseList?v=3";
import { blob } from "https://esm.town/v/std/blob";
import { set } from "https://esm.town/v/std/set?v=11";
import { addDays } from "https://esm.town/v/vlad/addDays";
import { formatDateToRoam } from "https://esm.town/v/vlad/formatDateToRoam";
import { sendMatrixChatRoomTextMessage } from "https://esm.town/v/vlad/sendMatrixChatRoomTextMessage";
import process from "node:process";
export const watchReaderAndSendToMatrix = async () => {
const lastProcessedReadwiseItemDate = (await blob.getJSON("lastProcessedReadwiseItemDate")).date;
console.log({ lastProcessedReadwiseItemDate });
const itemList = await fetchReadwiseList(
process.env.readwise,
"new",
);
const lastSavedIdx = itemList.results.findIndex((it) =>
new Date(it.created_at)
<= new Date(lastProcessedReadwiseItemDate)
);
const newItemsToSave: Array<any> = itemList.results.slice(0, lastSavedIdx);
console.log(`saving ${newItemsToSave.length} articles`, newItemsToSave);
const tomorrow = await formatDateToRoam(
addDays(new Date(), 1),
);
const messageFromReadwiseItem = (item) =>
`[[${item.title}]] by ${item.author} \n url: ${item.url} \nvia ${item.source_url}
\n ${item.summary}
\n [[to/read]] [[${tomorrow}]]`;
for (const it of newItemsToSave) {
await sendMatrixChatRoomTextMessage(
process.env.matrixOpenWhisperer,
process.env.matrixRoamSyncRoomId,
messageFromReadwiseItem(it),
);
}
if (newItemsToSave[0]) {
await blob.setJSON("lastProcessedReadwiseItemDate", { date: newItemsToSave[0].created_at });
}
};