# -*- coding: utf-8 -*-
# trilium_fix_diacritics.py
# Oprava diakritiky u testovacich poznamek pod slozkou Claude (ETAPI, UTF-8).
import json, urllib.request

BASE = "https://trilium.buzalka.cz/etapi"
TOKEN = "WoPH9O8hn2y6_r6pQSjpOVSmuL0os2hIQsLBHDOawebOx8l+MUc8v+GE="

def req(method, path, data=None, ctype="application/json; charset=utf-8"):
    body = None
    if data is not None:
        body = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode("utf-8")
    r = urllib.request.Request(BASE + path, data=body, method=method)
    r.add_header("Authorization", TOKEN)
    if body is not None:
        r.add_header("Content-Type", ctype)
    try:
        with urllib.request.urlopen(r) as resp:
            raw = resp.read().decode("utf-8")
            return json.loads(raw) if raw.strip().startswith(("{", "[")) else raw
    except urllib.error.HTTPError as e:
        print(f"  HTTP {e.code} na {method} {path}: {e.read().decode('utf-8', 'replace')}")
        raise

children = req("GET", "/notes/NeoXOIw0uBK2")["childNoteIds"]
for nid in children:
    content = req("GET", f"/notes/{nid}/content")
    if "Prvn" in content or "prvn" in content:
        title, html = "Test 1 (starší)", "<p>První poznámka.</p>"
    elif "Druh" in content or "druh" in content:
        title, html = "Test 2 (novější)", "<p>Druhá poznámka — měla by být nahoře.</p>"
    else:
        print(f"  {nid}: neznámý obsah, přeskakuji"); continue
    req("PATCH", f"/notes/{nid}", {"title": title})
    req("PUT", f"/notes/{nid}/content", html.encode("utf-8"), ctype="text/plain; charset=utf-8")
    print(f"  {nid} -> {title}")
print("Hotovo.")
