"""Small shared helper for the CRM's JSON files: atomic writes + an inter-process lock around a whole read-modify-write.

Why: the CRM runs in several worker processes. A plain `load -> change -> save(open(path, 'w'))` loses concurrent updates, lets a
reader see an empty/half-written file and, when a read error is swallowed as "empty", lets the next save wipe the store.

Contract
  * `read_json(path, default)`       lock-free read; always a complete file because writers replace it atomically.
  * `locked_json(path, default)`     `with` block = ONE transaction: exclusive lock -> read -> yield the data to change ->
                                      atomic write -> unlock. Nothing is written when the block raises, or when the data is
                                      unchanged. Do not nest it for the same path (it would wait for itself until the timeout).
  * `write_json_atomic(path, value)` atomic replacement without a read (for callers that own the whole content); takes the same
                                      lock, so it is ordered against transactions (never call it inside a block of the same path).
  * Temp files are named `.json-store-<sha256(file name)[:12]>-<random>.tmp`; leftovers of killed writers (> 1 h old) are removed
    only for the same store and only while holding that store's lock, so no active transaction can lose its temp file.
  * Fail closed: an unreadable/ill-typed file is NEVER treated as empty. A diagnostic copy `<file>.corrupt-<sha256[:12]>` is kept
    next to it (idempotent for identical content), the original is left untouched and JsonStoreCorrupt is raised.
  * The lock lives in `<file>.lock` (not on the data file: `os.replace` swaps the inode). 10 s timeout, then JsonStoreBusy.
  * Format is unchanged: UTF-8, ensure_ascii=False, indent=2. New files get mode 0o644 (as before); an existing file keeps its mode.
  * Windows (DEV): msvcrt.locking on byte 0 + retry of os.replace while a reader holds the target; POSIX (PROD): fcntl.flock +
    directory fsync. Symlinked data/lock paths are refused. Only the standard library; no environment, no SQL, no Flask.
"""
import contextlib
import copy
import hashlib
import json
import os
import shutil
import stat
import tempfile
import time

LOCK_TIMEOUT_SECONDS = 10.0
_LOCK_POLL_SECONDS = 0.005
_REPLACE_RETRY_SECONDS = 2.0


class JsonStoreError(Exception):
    """Base class: the store could not be used safely. `code` is stable for API responses."""
    code = 'json_store_error'


class JsonStoreBusy(JsonStoreError):
    code = 'json_store_busy'


class JsonStoreCorrupt(JsonStoreError):
    code = 'json_store_corrupt'

    def __init__(self, path, reason, diagnostic_copy=None):
        super().__init__(f'JSON store {os.path.basename(os.fspath(path))} is unreadable: {reason}')
        self.path = os.fspath(path)
        self.reason = reason
        self.diagnostic_copy = diagnostic_copy


class JsonStoreUnsafePath(JsonStoreError):
    code = 'json_store_unsafe_path'


def _check_path(path):
    path = os.fspath(path)
    if os.path.islink(path) or os.path.islink(path + '.lock'):
        raise JsonStoreUnsafePath(f'refusing a symlinked JSON store path: {os.path.basename(path)}')
    return path


def _parse(path, raw, kind):
    try:
        value = json.loads(raw.decode('utf-8'))
    except (UnicodeDecodeError, ValueError) as exc:
        raise JsonStoreCorrupt(path, f'{type(exc).__name__}: {exc}', _keep_diagnostic_copy(path, raw)) from None
    if not isinstance(value, kind):
        raise JsonStoreCorrupt(path, f'expected {kind.__name__}, found {type(value).__name__}', _keep_diagnostic_copy(path, raw))
    return value


def _keep_diagnostic_copy(path, raw):
    target = f'{path}.corrupt-{hashlib.sha256(raw).hexdigest()[:12]}'
    if not os.path.exists(target):
        try:
            with open(target, 'xb') as stream:
                stream.write(raw)
        except OSError:
            return None
    return target


def read_json(path, default):
    """Current content, `default()` when the file does not exist. Raises JsonStoreCorrupt for an unreadable/ill-typed file."""
    path = _check_path(path)
    kind = type(default())
    try:
        with open(path, 'rb') as stream:
            raw = stream.read()
    except FileNotFoundError:
        return default()
    return _parse(path, raw, kind)


def _serialize(value):
    return json.dumps(value, ensure_ascii=False, indent=2)


def _replace(source, target):
    deadline = time.monotonic() + _REPLACE_RETRY_SECONDS
    while True:
        try:
            return os.replace(source, target)
        except PermissionError:               # Windows: a reader still holds the target open
            if time.monotonic() > deadline:
                raise
            time.sleep(0.01)


_TEMP_SUFFIX = '.tmp'
_STALE_TEMP_SECONDS = 3600


def _temp_prefix(path):
    """Temp files are bound to ONE store: `.json-store-<sha256(file name)[:12]>-<random>.tmp` (same directory as the store)."""
    token = hashlib.sha256(os.path.basename(path).encode('utf-8')).hexdigest()[:12]
    return f'.json-store-{token}-'


def _atomic_write(path, text):
    directory = os.path.dirname(path) or '.'
    os.makedirs(directory, exist_ok=True)
    try:
        mode = stat.S_IMODE(os.stat(path).st_mode)
    except FileNotFoundError:
        mode = 0o644
    descriptor, temporary = tempfile.mkstemp(prefix=_temp_prefix(path), suffix=_TEMP_SUFFIX, dir=directory)
    try:
        with os.fdopen(descriptor, 'w', encoding='utf-8', newline='') as stream:
            stream.write(text)
            stream.flush()
            os.fsync(stream.fileno())
        if os.name == 'posix':
            os.chmod(temporary, mode)
        _replace(temporary, path)
        if os.name == 'posix':
            directory_fd = os.open(directory, os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0))
            try:
                os.fsync(directory_fd)
            finally:
                os.close(directory_fd)
    finally:
        if os.path.exists(temporary):
            with contextlib.suppress(OSError):
                os.unlink(temporary)


def _remove_stale_temp_files(path):
    """Drop leftovers of writers killed between mkstemp and os.replace - for THIS store only, older than an hour (best effort).

    Must be called while holding the store's lock: every temp file of this store belongs to a writer that holds that same lock,
    so an active transaction can never lose its temp file to a cleaner, whatever the age threshold. Other stores in the same
    directory have a different temp prefix and are never touched."""
    directory = os.path.dirname(path) or '.'
    prefix = _temp_prefix(path)
    try:
        with os.scandir(directory) as entries:
            for entry in entries:
                if entry.name.startswith(prefix) and entry.name.endswith(_TEMP_SUFFIX):
                    with contextlib.suppress(OSError):
                        if time.time() - entry.stat().st_mtime > _STALE_TEMP_SECONDS:
                            os.unlink(entry.path)
    except OSError:
        pass


def write_json_atomic(path, value, timeout=None):
    """Atomically replace the file with `value` (no read): only for callers that own the whole content. Takes the store's lock
    (so it is ordered against transactions) - never call it from inside a `locked_json` block of the same path."""
    timeout = LOCK_TIMEOUT_SECONDS if timeout is None else timeout
    path = _check_path(path)
    with _exclusive(path, timeout):
        _atomic_write(path, _serialize(value))
        _remove_stale_temp_files(path)


def _try_lock(descriptor):
    if os.name == 'nt':
        import msvcrt
        os.lseek(descriptor, 0, os.SEEK_SET)
        msvcrt.locking(descriptor, msvcrt.LK_NBLCK, 1)
    else:
        import fcntl
        fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)


def _unlock(descriptor):
    if os.name == 'nt':
        import msvcrt
        os.lseek(descriptor, 0, os.SEEK_SET)
        msvcrt.locking(descriptor, msvcrt.LK_UNLCK, 1)
    else:
        import fcntl
        fcntl.flock(descriptor, fcntl.LOCK_UN)


@contextlib.contextmanager
def _exclusive(path, timeout):
    lock_path = path + '.lock'
    os.makedirs(os.path.dirname(path) or '.', exist_ok=True)
    descriptor = os.open(lock_path, os.O_RDWR | os.O_CREAT | getattr(os, 'O_NOFOLLOW', 0), 0o600)
    acquired = False
    try:
        if not stat.S_ISREG(os.fstat(descriptor).st_mode):
            raise JsonStoreUnsafePath('the JSON store lock is not a regular file')
        # (Windows: byte 0 is locked even though the file is empty - locking beyond EOF is legal, and writing a marker byte
        # here would itself fail with PermissionError while another process holds that byte.)
        deadline = time.monotonic() + timeout
        while True:
            try:
                _try_lock(descriptor)
                acquired = True
                break
            except OSError:
                if time.monotonic() >= deadline:
                    raise JsonStoreBusy(f'timed out after {timeout:g}s waiting for {os.path.basename(path)}') from None
                time.sleep(_LOCK_POLL_SECONDS)
        yield
    finally:
        if acquired:
            with contextlib.suppress(OSError):
                _unlock(descriptor)
        os.close(descriptor)


@contextlib.contextmanager
def locked_json(path, default, timeout=None):
    """One read-modify-write transaction. `default` is a factory (list / dict); the yielded value is mutated in place.
    `timeout` defaults to LOCK_TIMEOUT_SECONDS (resolved at call time)."""
    timeout = LOCK_TIMEOUT_SECONDS if timeout is None else timeout
    path = _check_path(path)
    kind = type(default())
    with _exclusive(path, timeout):
        try:
            with open(path, 'rb') as stream:
                raw = stream.read()
            data = _parse(path, raw, kind)
        except FileNotFoundError:
            data = default()
        original = copy.deepcopy(data)
        yield data                      # an exception raised by the caller propagates from here: nothing below runs
        if data == original:
            return                      # no real change (also: missing file and nothing added) -> no write
        _atomic_write(path, _serialize(data))
        _remove_stale_temp_files(path)          # still under this store's lock
