"""Gitea Wiki helper: list, read, create, update wiki pages.

Usage:
  wiki_helper.py list                     — list all pages
  wiki_helper.py read <title>             — read a page
  wiki_helper.py create <title> <file>    — create a page from file
  wiki_helper.py update <title> <file>    — update a page from file
"""
import sys, io, json, base64, urllib.request, urllib.error

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# ============================================================
# ⚙️ CONFIGURATION — GITEA_REPO만 프로젝트별로 변경하세요
# ============================================================
GITEA_BASE_URL = "https://git.variet.net"
GITEA_OWNER = "Variet"
GITEA_REPO = "guitar_score"                       # guitar_score 프로젝트
GITEA_TOKEN = "3a01b4b15a39921572e64c413353e870d4d2161b"
# ============================================================

BASE = f"{GITEA_BASE_URL}/api/v1/repos/{GITEA_OWNER}/{GITEA_REPO}/wiki"
HEADERS = {"Authorization": f"token {GITEA_TOKEN}", "Content-Type": "application/json"}

def _req(method, path, data=None):
    url = f"{BASE}{path}"
    body = json.dumps(data).encode() if data else None
    req = urllib.request.Request(url, data=body, headers=HEADERS, method=method)
    try:
        with urllib.request.urlopen(req) as resp:
            return json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        err = e.read().decode()
        print(f"  ⚠️ HTTP {e.code}: {err}")
        return None

def _find_sub_url(title):
    pages = _req("GET", "/pages")
    if pages:
        for p in pages:
            if p.get("title", "").lower() == title.lower():
                return p.get("sub_url", title)
    return title

def list_pages():
    pages = _req("GET", "/pages")
    if pages:
        print(f"=== {len(pages)} Wiki Pages ===")
        for p in pages:
            print(f"  {p.get('title', '?')}")
    return pages

def read_page(title):
    sub = _find_sub_url(title)
    page = _req("GET", f"/page/{sub}")
    if page and page.get("content_base64"):
        content = base64.b64decode(page["content_base64"]).decode("utf-8")
        return content
    return None

def create_page(title, content):
    data = {
        "title": title,
        "content_base64": base64.b64encode(content.encode()).decode(),
    }
    result = _req("POST", "/new", data)
    if result:
        print(f"  ✅ Created wiki page: {title}")
    return result

def update_page(title, content):
    sub = _find_sub_url(title)
    data = {
        "title": title,
        "content_base64": base64.b64encode(content.encode()).decode(),
    }
    result = _req("PATCH", f"/page/{sub}", data)
    if result:
        print(f"  ✅ Updated wiki page: {title}")
    return result

if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "list"

    if cmd == "list":
        list_pages()
    elif cmd == "read" and len(sys.argv) > 2:
        content = read_page(sys.argv[2])
        if content:
            print(content[:5000])
        else:
            print(f"  Page '{sys.argv[2]}' not found")
    elif cmd == "create" and len(sys.argv) > 3:
        with open(sys.argv[3], "r", encoding="utf-8") as f:
            create_page(sys.argv[2], f.read())
    elif cmd == "update" and len(sys.argv) > 3:
        with open(sys.argv[3], "r", encoding="utf-8") as f:
            update_page(sys.argv[2], f.read())
    else:
        print("Usage: wiki_helper.py list|read <title>|create <title> <file>|update <title> <file>")
