"""Module for managing machine ID based on MAC address or system-generated ID."""

from pathlib import Path
from typing import Optional

from zscams.agent.src.support.configuration import config
from zscams.agent.src.support.filesystem import ensure_dir


MACHINE_ID_PATH = Path(config.must_get("config_dir")).joinpath("machine_id")


def get_machine_id():
    """Get the machine ID, either from the file or by using the MAC address."""
    try:
        return MACHINE_ID_PATH.read_text("utf-8").strip() or None
    except FileNotFoundError:
        return None


def set_machine_id(machine_id: Optional[str]):
    """Get the machine ID, either from the file or by using the MAC address."""
    ensure_dir(MACHINE_ID_PATH.parent)

    if not machine_id and MACHINE_ID_PATH.exists():
        return MACHINE_ID_PATH.unlink()

    if not machine_id:
        return

    return MACHINE_ID_PATH.write_text(machine_id, "utf-8")
