"""Low-level scheduler state: the private `DATA_DIR/scheduler` directory, its small JSON files and the one cross-process runner lock.

Moved unchanged out of `scheduled_jobs` (S4.4) so that the export modules can use these primitives without importing the cron executor.
Imports only the standard library and `storage_paths`; importing this module never starts or writes anything.
"""
from contextlib import contextmanager
import json
import os
import stat
import tempfile

from modules.core import storage_paths


class SchedulerError(Exception):
    """Safe, stable diagnostic code; never contains private paths."""


def _json_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("Duplicate JSON key")
        result[key] = value
    return result


def _directory(create=False):
    root = storage_paths.data_dir()
    if root is None:
        raise SchedulerError("external_data_dir_required")
    path = root / "scheduler"
    # Reject links/junctions in the entire private path, including absent leaves.
    for part in (path, *path.parents):
        if part.is_symlink() or (hasattr(part, "is_junction") and part.is_junction()):
            raise SchedulerError("unsafe_scheduler_path")
    if create:
        path.mkdir(mode=0o700, parents=True, exist_ok=True)
    return path


def _read(name, default):
    path = _directory() / name
    try:
        fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
                     | getattr(os, "O_BINARY", 0) | getattr(os, "O_NONBLOCK", 0))
    except FileNotFoundError:
        return default
    try:
        before = os.fstat(fd)
        if not stat.S_ISREG(before.st_mode) or path.is_symlink() or before.st_size > 65536:
            raise SchedulerError("invalid_" + name)
        with os.fdopen(fd, "rb", closefd=False) as stream:
            raw = stream.read(65537)
        if len(raw) > 65536:
            raise ValueError()
        return json.loads(raw, object_pairs_hook=_json_object)
    except (ValueError, UnicodeError, RecursionError):
        raise SchedulerError("invalid_" + name) from None
    finally:
        os.close(fd)


def _write(name, value):
    root = _directory(create=True)
    target = root / name
    if target.is_symlink():
        raise SchedulerError("unsafe_scheduler_path")
    fd, temporary = tempfile.mkstemp(prefix=".scheduler-", dir=root)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as stream:
            json.dump(value, stream, ensure_ascii=True, allow_nan=False)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temporary, target)
        if os.name == "posix":
            directory_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
            try:
                os.fsync(directory_fd)
            finally:
                os.close(directory_fd)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)


@contextmanager
def runner_lock():
    """One nonblocking OS lock for tick and configuration changes, not WSGI threads."""
    path = _directory(create=True) / "runner.lock"
    fd = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600)
    acquired = False
    try:
        if path.is_symlink() or not stat.S_ISREG(os.fstat(fd).st_mode):
            raise SchedulerError("unsafe_scheduler_path")
        if os.name == "posix":
            import fcntl
            try:
                fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
                acquired = True
            except BlockingIOError:
                pass
        elif os.name == "nt":
            import msvcrt
            if os.fstat(fd).st_size == 0:
                os.write(fd, b"0")
            os.lseek(fd, 0, os.SEEK_SET)
            try:
                msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
                acquired = True
            except OSError:
                pass
        else:
            raise SchedulerError("unsupported_lock_platform")
        yield acquired
    finally:
        if acquired:
            if os.name == "posix":
                fcntl.flock(fd, fcntl.LOCK_UN)
            else:
                os.lseek(fd, 0, os.SEEK_SET)
                msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
        os.close(fd)


# Public names for other modules (the underscore names above are the historical ones and stay in use inside the scheduler).
directory = _directory
read = _read
write = _write
json_object = _json_object
