from __future__ import annotations

import string

from one_run.constants import ALLOWED_PLACEHOLDERS
from one_run.errors import TemplateError


def validate_placeholders(template: str) -> None:
    formatter = string.Formatter()
    for _, field_name, _, _ in formatter.parse(template):
        if field_name is None:
            continue
        if field_name not in ALLOWED_PLACEHOLDERS:
            allowed = ", ".join(sorted(ALLOWED_PLACEHOLDERS))
            raise TemplateError(f"unknown placeholder '{field_name}'. allowed: {allowed}")


def render_command(template: str, values: dict[str, str | int]) -> str:
    validate_placeholders(template)
    try:
        return template.format(**values)
    except KeyError as exc:
        raise TemplateError(f"missing value for placeholder: {exc.args[0]}") from exc
