"""Shared Jinja2 environment and preamble/postamble for pygitweb templates."""

from collections.abc import Iterable

from jinja2 import Environment, PackageLoader, select_autoescape
from markupsafe import Markup

env = Environment(
	loader=PackageLoader("pygitweb", "templates"),
	autoescape=select_autoescape(enabled_extensions=("html", "xml"), default_for_string=True),
	trim_blocks=True,
	lstrip_blocks=True,
)
PREAMBLE = env.get_template("preamble.html")
POSTAMBLE = """</div></div></div></body></html>"""

# A table cell is plain text, which the template escapes, or Markup, which it does not.
Cell = str | Markup

_ESCAPE_TEMPLATE = env.from_string("{{ value|e }}")


def jinja_escape(value: str | None) -> str | None:
	if value is None:
		return None
	return _ESCAPE_TEMPLATE.render(value=value)


def html_link(href: str, text: str, **attrs: str) -> Markup:
	"""Anchor tag. href, text, and attribute values are escaped."""
	attr_html = Markup("").join(
		Markup(' {}="{}"').format(name.replace("_", "-"), value) for name, value in attrs.items()
	)
	return Markup('<a href="{}"{}>{}</a>').format(href, attr_html, text)


def html_format(template: str, /, *args: object, **kwargs: object) -> Markup:
	"""Format an HTML snippet, escaping interpolated values. The template itself is trusted."""
	return Markup(template).format(*args, **kwargs)


def html_join(parts: Iterable[str | Markup], sep: str = "") -> Markup:
	"""Join fragments. Plain strings are escaped; Markup is inserted as-is."""
	return Markup(sep).join(parts)


def trusted_html(value: str) -> Markup:
	"""Mark HTML that a template or plugin already escaped. Do not pass raw text."""
	return Markup(value)