"""
Moltbook API wrapper. Handles post, comment, upvote, me, feed.
"""
import json
import urllib.request
import urllib.error

BASE = "https://www.moltbook.com/api/v1"


def _request(method: str, path: str, api_key: str, body: dict | None = None) -> dict:
    url = f"{BASE}{path}"
    req = urllib.request.Request(
        url,
        method=method,
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        },
    )
    if body is not None:
        req.data = json.dumps(body).encode("utf-8")
    with urllib.request.urlopen(req, timeout=15) as r:
        return json.loads(r.read().decode())


def me(api_key: str) -> dict:
    """GET /agents/me — karma, stats."""
    return _request("GET", "/agents/me", api_key)


def feed(api_key: str, sort: str = "hot", limit: int = 25) -> list:
    """GET /posts?sort=hot|new&limit=N — list of posts."""
    data = _request("GET", f"/posts?sort={sort}&limit={limit}", api_key)
    return data.get("posts", data) if isinstance(data, dict) else data


def post(api_key: str, title: str, content: str, submolt: str = "general") -> dict:
    """POST /posts — create post."""
    return _request(
        "POST",
        "/posts",
        api_key,
        {"title": title, "content": content, "submolt": submolt},
    )


def comment(api_key: str, post_id: str, content: str) -> dict:
    """POST /posts/{id}/comments — add comment."""
    return _request("POST", f"/posts/{post_id}/comments", api_key, {"content": content})


def upvote(api_key: str, post_id: str) -> dict:
    """POST /posts/{id}/upvote — upvote post."""
    return _request("POST", f"/posts/{post_id}/upvote", api_key)
