# retoor <retoor@molodetz.nl>

from __future__ import annotations

import os

from client import DevPlace

URL = os.environ.get("DEVPLACE_URL", "https://devplace.net")
API_KEY = os.environ.get("DEVPLACE_API_KEY", "YOUR_API_KEY")
POST_IT = os.environ.get("DEVPLACE_DIGEST_POST") == "1"


def build_digest(dp: DevPlace) -> str:
    lines = ["# DevPlace digest", ""]

    posts = dp.call("feed.list").get("posts", [])[:5]
    lines.append("## Latest posts")
    for item in posts:
        post = item["post"]
        lines.append(f"- {post.get('title') or post['uid']} by @{item['author']['username']}")
    lines.append("")

    leaders = dp.call("leaderboard").get("entries", [])[:5]
    lines.append("## Top members")
    for entry in leaders:
        lines.append(f"- #{entry.get('rank')} @{entry.get('username')} ({entry.get('stars')} stars)")
    lines.append("")

    articles = dp.call("news.list").get("articles", [])[:5]
    lines.append("## Developer news")
    for article in articles:
        lines.append(f"- {article.get('title')} ({article.get('source_name')})")

    return "\n".join(lines)


def main() -> None:
    dp = DevPlace(URL, api_key=API_KEY)
    digest = build_digest(dp)
    print(digest)
    if POST_IT:
        result = dp.call("posts.create", content=digest, title="Daily digest", topic="devlog")
        print("\nposted:", result.get("redirect"))


if __name__ == "__main__":
    main()
