"""Cross-process safe JSONL append.

Single helper used by every JSONL audit-log appender to share the
fcntl.flock + fsync pattern. Caller owns serialization and any outer
lock (threading.RLock, try/except for best-effort callers).
"""

from __future__ import annotations

import fcntl
import os
from pathlib import Path


def append_jsonl_locked(path: Path, line: str, *, fsync: bool = True) -> None:
    """Append one pre-serialized JSONL line under fcntl.LOCK_EX.

    Args:
        path: Target log file (parent dirs created on demand).
        line: Pre-serialized JSON record, trailing newline included.
        fsync: When True (default), os.fsync after flush — durable write.

    Caller owns serialization (`json.dumps(...)`, `to_dict()`, etc.) and
    any outer locking + error handling.
    """
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("a", encoding="utf-8") as f:
        fcntl.flock(f, fcntl.LOCK_EX)
        try:
            f.write(line)
            f.flush()
            if fsync:
                os.fsync(f.fileno())
        finally:
            fcntl.flock(f, fcntl.LOCK_UN)


__all__ = ["append_jsonl_locked"]
