import re
from dataclasses import asdict, dataclass


@dataclass
class KPI:
    """Metric with name, value, unit and display precision."""

    name: str
    value: float
    unit: str | None = None
    precision: int = 2
    NAME_AND_UNIT = re.compile(r"^(.*?) \[(.*?)\]$")

    def __post_init__(self):
        """Move units embedded in column names (e.g. 'Area [m²]') into the unit field."""
        if match := self.NAME_AND_UNIT.match(self.name):
            self.name, self.unit = match.groups()

    def to_dict(self) -> dict:
        return asdict(self)

    @property
    def rounded_value(self) -> float:
        return round(self.value, self.precision)

    def __str__(self):
        s = f"{self.name:35s} : {self.value:.{self.precision}f}"
        if self.unit:
            s = f"{s} {self.unit}"
        return s

    def __repr__(self):
        return str(self)

    @classmethod
    def from_dict(cls, data: dict) -> "KPI":
        return cls(**data)
