"""Gitea API client."""

import json
import logging
import urllib.request
import urllib.error

log = logging.getLogger(__name__)

GITEA_URL = "https://git.vish.gg"
GITEA_TOKEN = "REDACTED_TOKEN"  # pragma: allowlist secret
DEFAULT_REPO = "vish/homelab"


def gitea_api(method: str, path: str, data: dict | None = None,
              url: str = GITEA_URL, token: str = GITEA_TOKEN) -> dict | list:
    """Make a Gitea API request."""
    full_url = f"{url.rstrip('/')}/api/v1/{path.lstrip('/')}"
    body = json.dumps(data).encode() if data else None
    req = urllib.request.Request(full_url, data=body, method=method, headers={
        "Authorization": f"token {token}",
        "Content-Type": "application/json",
        "Accept": "application/json",
    })
    with urllib.request.urlopen(req, timeout=30) as resp:
        return json.loads(resp.read())


def get_commits_since(since: str, repo: str = DEFAULT_REPO) -> list[dict]:
    """Get commits since an ISO timestamp."""
    return gitea_api("GET", f"repos/{repo}/commits?sha=main&limit=50&since={since}")


def create_release(tag: str, title: str, body: str, repo: str = DEFAULT_REPO) -> dict:
    """Create a Gitea release."""
    return gitea_api("POST", f"repos/{repo}/releases", data={
        "tag_name": tag, "name": title, "body": body, "draft": False, "prerelease": False,
    })
