# retoor <retoor@molodetz.nl>

import os
import time

from client import from_env

POLL_SECONDS = int(os.environ.get("DEVRANT_POLL_SECONDS", "30"))
UPVOTE_KEYWORDS = [
    word.strip().lower()
    for word in os.environ.get("DEVRANT_UPVOTE_KEYWORDS", "").split(",")
    if word.strip()
]


def main() -> None:
    api = from_env()
    if api.username and api.password:
        api.login()
    seen: set[int] = set()
    print(f"watching feed every {POLL_SECONDS}s (ctrl-c to stop)")
    while True:
        for rant in reversed(api.rants(sort="recent", limit=20)):
            rant_id = rant["id"]
            if rant_id in seen:
                continue
            seen.add(rant_id)
            text = rant["text"].replace("\n", " ")[:80]
            print(f"[{rant_id}] {rant['user_username']}: {text}")
            if UPVOTE_KEYWORDS and api.auth:
                lowered = rant["text"].lower()
                if any(word in lowered for word in UPVOTE_KEYWORDS):
                    api.vote_rant(rant_id, 1)
                    print(f"  upvoted {rant_id}")
        time.sleep(POLL_SECONDS)


if __name__ == "__main__":
    main()
