import socket

import uuid
from dataclasses import dataclass, field
from functools import cached_property

get_hostname = socket.gethostname
get_fqdn = socket.getfqdn


@dataclass(frozen=True)
class MAC:
    value: int = field(default_factory=uuid.getnode)

    @classmethod
    def from_string(cls, s: str):
        """

        Initialise from a string.

        """
        s = s.lower().replace(":", "").replace("-", "")
        return cls(int(s, 16))

    @cached_property
    def int(self):
        return self.value

    @cached_property
    def hex(self):
        """

        Plain 12-character hex string, no separators.

        """
        return f"{self.value:012x}"

    @cached_property
    def components(self):
        """

        Return list of six 2-digit hex strings.

        """
        h = self.hex
        return [h[i:i + 2] for i in range(0, 12, 2)]

    @cached_property
    def hex_colon(self):
        """

        Colon-separated hex string (default standard).

        """
        return self.string(":")

    @cached_property
    def is_random(self) -> bool:
        """

        Detect if this MAC is likely randomly generated by uuid.getnode().
        Checks the "multicast" bit (bit 1 of the first byte).

        """
        return bool(self.value & (1 << 40))

    def string(self, sep: str = ":") -> str:
        """

        Return MAC as a string with separator `sep`.

        """
        return sep.join(self.components)
