# retoor <retoor@molodetz.nl>

from __future__ import annotations

import os
import time
import xmlrpc.client

from client import DevPlace

URL = os.environ.get("DEVPLACE_URL", "https://devplace.net")
API_KEY = os.environ.get("DEVPLACE_API_KEY", "YOUR_API_KEY")
POLL_SECONDS = int(os.environ.get("DEVPLACE_POLL_SECONDS", "20"))
UPVOTE_KEYWORDS = [k.strip().lower() for k in os.environ.get("DEVPLACE_UPVOTE_KEYWORDS", "").split(",") if k.strip()]


def matches(post: dict) -> bool:
    if not UPVOTE_KEYWORDS:
        return False
    haystack = f"{post.get('title') or ''} {post.get('content') or ''}".lower()
    return any(keyword in haystack for keyword in UPVOTE_KEYWORDS)


def run() -> None:
    dp = DevPlace(URL, api_key=API_KEY)
    seen: set[str] = set()
    primed = False
    print(f"Watching the feed on {URL}; Ctrl-C to quit.")
    if UPVOTE_KEYWORDS:
        print("Auto-upvoting posts matching:", ", ".join(UPVOTE_KEYWORDS))
    while True:
        try:
            for item in dp.call("feed.list").get("posts", []):
                post = item["post"]
                if post["uid"] in seen:
                    continue
                seen.add(post["uid"])
                if not primed:
                    continue
                author = item["author"]["username"]
                print(f"[{item.get('time_ago')}] @{author}: {post.get('title') or post['uid']}")
                if API_KEY != "YOUR_API_KEY" and matches(post):
                    try:
                        dp.call("votes.cast", target_type="post", target_uid=post["uid"], value="1")
                        print("  upvoted (keyword match)")
                    except xmlrpc.client.Fault as fault:
                        print("  upvote failed:", fault.faultCode)
            primed = True
        except xmlrpc.client.Fault as fault:
            print("error:", fault.faultCode, fault.faultString)
        except OSError as error:
            print("network error:", error)
        time.sleep(POLL_SECONDS)


if __name__ == "__main__":
    run()
