# retoor <retoor@molodetz.nl>

from __future__ import annotations

import os
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")
OUT_DIR = Path(os.environ.get("DEVPLACE_GIST_DIR", "gists_backup"))

EXTENSIONS = {
    "python": "py",
    "javascript": "js",
    "typescript": "ts",
    "html": "html",
    "css": "css",
    "c": "c",
    "cpp": "cpp",
    "java": "java",
    "go": "go",
    "rust": "rs",
    "sql": "sql",
    "bash": "sh",
    "json": "json",
    "markdown": "md",
    "plaintext": "txt",
}


def all_gists(dp: DevPlace):
    cursor = None
    while True:
        page = dp.call("gists.list", before=cursor) if cursor else dp.call("gists.list")
        for item in page.get("gists", []):
            yield item["gist"]
        cursor = page.get("next_cursor")
        if not cursor:
            return


def main() -> None:
    dp = DevPlace(URL, api_key=API_KEY)
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    saved = 0
    for gist in all_gists(dp):
        extension = EXTENSIONS.get(gist.get("language") or "plaintext", "txt")
        path = OUT_DIR / f"{gist['slug']}.{extension}"
        path.write_text(gist.get("source_code") or "", encoding="utf-8")
        saved += 1
        print("saved", path)
    print(f"backed up {saved} gists into {OUT_DIR}/")


if __name__ == "__main__":
    main()
