# retoor <retoor@molodetz.nl>

from __future__ import annotations

import json
import os
import sys
from pathlib import Path

from client import DevPlace

URL = os.environ.get("DEVPLACE_URL", "https://devplace.net")
API_KEY = os.environ.get("DEVPLACE_API_KEY", "YOUR_API_KEY")
USERNAME = os.environ.get("DEVPLACE_USERNAME") or (sys.argv[1] if len(sys.argv) > 1 else "")
OUT_FILE = Path(os.environ.get("DEVPLACE_EXPORT_FILE", "devplace_export.json"))


def main() -> None:
    if not USERNAME:
        print("Usage: DEVPLACE_USERNAME=<you> python export_data.py")
        return
    dp = DevPlace(URL, api_key=API_KEY)
    export = {
        "profile": dp.call("profile.detail", username=USERNAME),
        "posts": dp.call("profile.detail", username=USERNAME, tab="posts").get("posts", []),
        "gists": dp.call("profile.detail", username=USERNAME, tab="gists").get("gists", []),
        "projects": dp.call("profile.detail", username=USERNAME, tab="projects").get("projects", []),
        "bookmarks": dp.call("bookmarks.saved").get("items", []),
        "notifications": dp.call("notifications.list").get("notification_groups", []),
    }
    OUT_FILE.write_text(json.dumps(export, indent=2), encoding="utf-8")
    print(
        f"exported profile, {len(export['posts'])} posts, {len(export['gists'])} gists, "
        f"{len(export['projects'])} projects to {OUT_FILE}"
    )


if __name__ == "__main__":
    main()
