"""Minimal helpers for backlink generation."""

from __future__ import annotations

from html import escape
from typing import Optional


def build_backlink(url: str, text: Optional[str] = None, *, rel: str = "nofollow", target: str = "_blank") -> str:
    """Return a minimal HTML backlink anchor.

    Args:
        url: The destination URL.
        text: Visible anchor text. Defaults to the URL.
        rel: Rel attribute for the link.
        target: Target attribute for the link.
    """
    if not url:
        raise ValueError("url is required")

    label = url if text is None else text
    return (
        f'<a href="{escape(url, quote=True)}" '
        f'rel="{escape(rel, quote=True)}" '
        f'target="{escape(target, quote=True)}">{escape(label)}</a>'
    )