// retoor <retoor@molodetz.nl>

import { fromEnv } from "./client.mjs";

const pollSeconds = Number(process.env.DEVRANT_POLL_SECONDS || "30");
const keywords = (process.env.DEVRANT_UPVOTE_KEYWORDS || "")
  .split(",")
  .map((word) => word.trim().toLowerCase())
  .filter(Boolean);

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const api = fromEnv();
if (api.username && api.password) await api.login();

const seen = new Set();
console.log(`watching feed every ${pollSeconds}s (ctrl-c to stop)`);

while (true) {
  const rants = await api.rants("recent", 20);
  for (const rant of rants.reverse()) {
    if (seen.has(rant.id)) continue;
    seen.add(rant.id);
    const text = rant.text.replace(/\n/g, " ").slice(0, 80);
    console.log(`[${rant.id}] ${rant.user_username}: ${text}`);
    if (keywords.length && api.auth.token_key) {
      const lowered = rant.text.toLowerCase();
      if (keywords.some((word) => lowered.includes(word))) {
        await api.voteRant(rant.id, 1);
        console.log(`  upvoted ${rant.id}`);
      }
    }
  }
  await sleep(pollSeconds * 1000);
}
