from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable, Protocol


class AttributeKeyResolver(Protocol):
    def can_resolve(self, attribute: object) -> bool:
        ...

    def resolve(self, attribute: object) -> object:
        ...


@dataclass(frozen=True)
class TaggedAttributeKeyResolver:
    def can_resolve(self, attribute: object) -> bool:
        return all(hasattr(attribute, name) for name in ("tag", "value", "unit"))

    def resolve(self, attribute: object) -> object:
        return (
            getattr(attribute, "tag", None),
            getattr(attribute, "value", None),
            getattr(attribute, "unit", None),
        )


@dataclass(frozen=True)
class IdentityAttributeKeyResolver:
    def can_resolve(self, attribute: object) -> bool:
        return True

    def resolve(self, attribute: object) -> object:
        return attribute


class AttributeKeyResolverChain:
    def __init__(self, resolvers: Iterable[AttributeKeyResolver] | None = None):
        self._resolvers = list(resolvers) if resolvers else [
            TaggedAttributeKeyResolver(),
            IdentityAttributeKeyResolver(),
        ]

    def resolve(self, attribute: object) -> object:
        for resolver in self._resolvers:
            if resolver.can_resolve(attribute):
                return resolver.resolve(attribute)
        return attribute
