from __future__ import annotations

import fcntl
from pathlib import Path


class DreamLock:
    """dream 单 writer 文件锁（Docker worker 推荐节点）。"""

    def __init__(self, path: Path) -> None:
        self._path = path
        self._file = None

    @property
    def path(self) -> Path:
        return self._path

    def acquire(self) -> bool:
        self._path.parent.mkdir(parents=True, exist_ok=True)
        self._file = self._path.open("w", encoding="utf-8")
        try:
            fcntl.flock(self._file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            self._file.write("locked\n")
            self._file.flush()
            return True
        except BlockingIOError:
            self._file.close()
            self._file = None
            return False

    def release(self) -> None:
        if self._file is None:
            return
        try:
            fcntl.flock(self._file.fileno(), fcntl.LOCK_UN)
        finally:
            self._file.close()
            self._file = None

    def __enter__(self) -> bool:
        return self.acquire()

    def __exit__(self, *args: object) -> None:
        self.release()
