# retoor <retoor@molodetz.nl>

from __future__ import annotations

import os
import sys
import xmlrpc.client
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")
SOURCE = Path(os.environ.get("DEVPLACE_SOURCE") or (sys.argv[1] if len(sys.argv) > 1 else "."))
TITLE = os.environ.get("DEVPLACE_PROJECT_TITLE") or (sys.argv[2] if len(sys.argv) > 2 else SOURCE.resolve().name)

SKIP_DIRS = {".git", "__pycache__", "node_modules", ".venv", "venv"}
MAX_BYTES = 512 * 1024


def text_files(root: Path):
    for path in sorted(root.rglob("*")):
        if not path.is_file():
            continue
        if any(part in SKIP_DIRS for part in path.relative_to(root).parts):
            continue
        if path.stat().st_size > MAX_BYTES:
            print("skip (too big):", path)
            continue
        try:
            content = path.read_text(encoding="utf-8")
        except UnicodeDecodeError:
            print("skip (binary):", path)
            continue
        yield path.relative_to(root).as_posix(), content


def main() -> None:
    dp = DevPlace(URL, api_key=API_KEY)
    created = dp.call(
        "projects.create",
        title=TITLE,
        description=f"Deployed from {SOURCE} via the XML-RPC bridge.",
        project_type="software",
    )
    slug = created["data"]["slug"]
    print("created project:", slug)
    count = 0
    for rel_path, content in text_files(SOURCE):
        try:
            dp.call("project.files.write", project_slug=slug, path=rel_path, content=content)
            count += 1
            print("wrote", rel_path)
        except xmlrpc.client.Fault as fault:
            print("failed", rel_path, "-", fault.faultCode, fault.faultString)
    print(f"deployed {count} files to {URL}/projects/{slug}")


if __name__ == "__main__":
    main()
