from typing import Any

from .apptypes import (
    RenderingResult,
    RenderingResultSuccess,
)
from .rendering import CoalesceJinjaEnvironment
from .packages import DictPackageRegistry
from .errors import RendererError
from .readers import read_renderer_request
from .response import json_safe


def plain_render(dct: dict[str, Any]) -> RenderingResultSuccess:
    """Render a response from a request dictionary"""
    request = read_renderer_request(dct)
    registry = DictPackageRegistry()
    env = CoalesceJinjaEnvironment(registry, request.render_platform_kind)
    return env.render_coalesce_template_v2(request)


def render_from_dict(dct: dict[str, Any]) -> RenderingResult:
    """Render a response from a request dictionary, handling errors"""
    try:
        result = plain_render(dct)
        return json_safe(result)
    except RendererError as exc:
        return exc.response()
    except Exception as exc:
        return json_safe(
            {
                "error": {
                    "errorString": f"Template rendering error: {str(exc)}",
                    "errorDetail": f"Template rendering error: {str(exc)}",
                },
                "runDetails": None,
            }
        )
