import dataclasses

import forcen_public_utils.checked as ch


@dataclasses.dataclass(frozen=True)
class Version:
    major: int
    minor: int
    patch: int

    @staticmethod
    def from_str(version_str: str) -> ch.MaybeVal["Version"]:
        """Parse a Version from a string.

        Args:
            version_str (str): must be in the format "{any_char}{major}.{minor}.{patch}"
        """
        try:
            tokens = [int(ii) for ii in version_str.split(".")]
        except ValueError as e:
            return ch.bad(message=f"Failed to parse version parts as ints from [{version_str}]. Got {e}")

        if len(tokens) != 3:
            return ch.bad(
                message=f"Version string must contain 3 dot-separated numbers (x.y.z), got {version_str[1:]}"
            )

        return ch.ok(
            Version(
                major=tokens[0],
                minor=tokens[1],
                patch=tokens[2],
            )
        )

    def __str__(self) -> str:
        return f"{self.major}.{self.minor}.{self.patch}"

    def __hash__(self) -> int:
        return hash(repr(self))
