from __future__ import annotations

import re
from typing import Any

from .defaults import resolve_defaults


PLACEHOLDER_PATTERN = re.compile(r"\{\{([^}]+)\}\}")


def render_template(template: str, values: dict[str, Any]) -> str:
    def replace(match: re.Match[str]) -> str:
        key = match.group(1).strip()
        value = values.get(key, "")
        return "" if value is None else str(value)

    return PLACEHOLDER_PATTERN.sub(replace, template)


def render_form(
    form: dict[str, Any],
    global_defaults: dict[str, Any],
    encounter_values: dict[str, Any] | None = None,
) -> str:
    values = resolve_defaults(form, global_defaults, encounter_values)
    return render_template(form.get("narrative_template") or form.get("template", ""), values)
