"""Authored Jinja exercise. No model/API calls; renders trusted literal templates only."""
import json
import platform
from importlib.metadata import version
from jinja2 import Environment, StrictUndefined, UndefinedError

TEMPLATE = "Audience: {{ audience }}\nTask: {{ task }}\nConstraints: {{ constraints }}"
strict = Environment(undefined=StrictUndefined, autoescape=False)
complete = {"audience": "new project volunteers", "task": "Draft a welcome note", "constraints": "Use only the supplied facts. Ask about missing details."}

def required_text(context):
    """Our application policy: all three fields must be nonblank strings."""
    invalid = [key for key in ("audience", "task", "constraints")
               if not isinstance(context.get(key), str) or not context[key].strip()]
    if invalid:
        return {"status": "human_review_required", "fields": invalid}
    return {"status": "rendered", "prompt": strict.from_string(TEMPLATE).render(context)}

def run():
    missing = {k: v for k, v in complete.items() if k != "constraints"}
    default = Environment(autoescape=False).from_string(TEMPLATE).render(missing)
    assert default.endswith("Constraints: ")
    try:
        strict.from_string(TEMPLATE).render(missing)
    except UndefinedError as error:
        missing_result = {"error": type(error).__name__, "message": str(error)}
    else:
        raise AssertionError("Missing constraints did not raise")
    rendered = strict.from_string(TEMPLATE).render(complete)
    assert rendered.endswith(complete["constraints"])
    empty = strict.from_string(TEMPLATE).render({**complete, "constraints": ""})
    null = strict.from_string(TEMPLATE).render({**complete, "constraints": None})
    assert empty.endswith("Constraints: ") and null.endswith("Constraints: None")
    policy = []
    for label, value in [("missing", missing), ("empty", {**complete, "constraints": ""}),
                         ("whitespace", {**complete, "constraints": "  "}),
                         ("null", {**complete, "constraints": None})]:
        result = required_text(value)
        assert result == {"status": "human_review_required", "fields": ["constraints"]}
        policy.append({"case": label, **result})
    optional = strict.from_string("Tone: {{ tone | default('neutral') }}").render()
    assert optional == "Tone: neutral"
    braces = required_text({**complete, "task": "Explain the literal {{ audience }} token"})
    assert "{{ audience }}" in braces["prompt"]
    assert required_text(complete)["status"] == "rendered"
    return {"python": platform.python_version(), "jinja2": version("Jinja2"),
            "default_missing": default, "strict_missing": missing_result,
            "strict_complete": rendered, "strict_empty": empty, "strict_null": null,
            "required_text_policy": policy, "optional_default": optional,
            "braces_in_data": braces, "model_called": False}

if __name__ == "__main__":
    print(json.dumps(run(), indent=2))
