"""Windows compatibility for LiCSBAS multiprocessing.

On Linux, LiCSBAS uses fork-based multiprocessing which shares globals.
On Windows, fork is unavailable — spawn creates fresh processes that
don't inherit globals, causing NameError in worker functions.

This module provides a SequentialPool that runs tasks in the main process,
avoiding the issue entirely. It's used automatically on Windows.
"""

import sys


class SequentialPool:
    """Drop-in replacement for multiprocessing.Pool that runs sequentially.

    Provides the same interface (starmap, map, close) but executes in
    the calling process, avoiding Windows spawn/global issues.
    """

    def __init__(self, processes=None):
        pass

    def starmap(self, func, iterable):
        return [func(*args) for args in iterable]

    def map(self, func, iterable):
        return [func(x) for x in iterable]

    def close(self):
        pass

    def join(self):
        pass

    def __enter__(self):
        return self

    def __exit__(self, *args):
        pass


class SequentialContext:
    """Drop-in replacement for multiprocessing context on Windows."""

    def Pool(self, processes=None):
        return SequentialPool(processes)


def get_compatible_context():
    """Return a multiprocessing context that works on the current platform.

    On Linux/Mac: returns fork context (fast, shares memory)
    On Windows: returns SequentialContext (runs in main process)
    """
    if sys.platform == 'win32':
        return SequentialContext()
    else:
        import multiprocessing as multi
        return multi.get_context('fork')
