import string
from typing import Any


class FlagFormatter(string.Formatter):

    def vformat(self, format_string: str, args: tuple, kwargs: dict[str, Any]) -> str:
        try:
            return super().vformat(format_string, args, kwargs)
        except (KeyError, IndexError, AttributeError, TypeError, ValueError):
            return format_string

    def get_field(self, field_name: str, args: tuple, kwargs: dict[str, Any]) -> tuple[Any, str]:
        parts = field_name.split(".")
        first = parts[0]

        try:
            obj = self.get_value(first, args, kwargs)
        except (KeyError, IndexError):
            raise KeyError(first) from None

        for segment in parts[1:]:
            try:
                obj = getattr(obj, segment)
            except AttributeError:
                try:
                    obj = obj[segment]
                except (KeyError, TypeError, IndexError):
                    raise KeyError(field_name) from None

        return obj, first


flag_formatter = FlagFormatter()
