#!/usr/bin/env python3
"""Example Wan action.

The server runs an action on demand as:  <script> <noteId>
with RW_NOTE_ID and RW_BASE_URL set in the environment. This one sets a note's
title to the first non-empty line of its body, talking to the app's own HTTP API
— the same API the browser uses — so the change broadcasts and the open card
updates live.

Actions are just executables: this is Python, but a shell script, a compiled
binary, or anything else works, as long as it talks to RW_BASE_URL. To enable an
action, drop it (executable) into the actions directory (default ./actions).
"""
import json
import os
import sys
import urllib.request

note_id = sys.argv[1] if len(sys.argv) > 1 else os.environ["RW_NOTE_ID"]
base = os.environ.get("RW_BASE_URL", "http://127.0.0.1:8123")


def api(method, path, body=None):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(
        f"{base}{path}", data=data, method=method,
        headers={"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(req) as resp:
        raw = resp.read()
        return json.loads(raw) if raw else None


note = api("GET", f"/api/notes/{note_id}")
title = next((ln.lstrip("#").strip() for ln in note.get("body", "").splitlines() if ln.strip()), "")
if not title:
    sys.exit("note has no text to make a title from")

# The API's PUT replaces the whole note, so carry the other fields through.
api("PUT", f"/api/notes/{note_id}", {
    "title": title,
    "body": note.get("body", ""),
    "tags": note.get("tags", []),
    "source": note.get("source", ""),
})
print(f"set title to: {title}")
