import os
import platform
import pytest
import shutil
import time

from pathlib import Path

import wox.subprocessor as subprocessor

from tests.resources.constants import RAMDISK_PATH


@pytest.fixture(scope = 'session')
def tmpfs():
    """
        Mounts a RAM disk and fills it with data.

        Notes
        -----
        During tests, `test_pip_disk_full()` can get stuck on the pip install step.
        To work around this, the test uses a timeout and retries. On retry, the test
        manages to attempt the installation on the RAM disk and raises DiskFullError.

        If the fixture had function scope, teardown would trigger between retries
        and the retry would create a new RAM disk, breaking the test.

        Setting the scope to 'session' ensures the fixture persists across retries.

        Additionally, this fixture is shared between the pip install test and
        its counterpart, uv pip install.
        Somehow, if pip has already attempted to install pandas in the RAM disk,
        the uv test fails.

        The proper workaround is to run the uv test first, then the pip test.

        By doing so, the pip test doesn’t even need to retry, since the uv test
        has already prepared the fixture.
    """

    if platform.system() != 'Linux':
        pytest.skip('tmpfs only works on Linux')

    if not shutil.which('sudo'):
        pytest.skip('tmpfs requires sudo')

    if not RAMDISK_PATH.exists():
        Path.mkdir(RAMDISK_PATH, parents = True)

        filler_file = RAMDISK_PATH / 'fill.txt'

        subprocessor.run_command(f'sudo mount -t tmpfs -o size=1M tmpfs {RAMDISK_PATH}')

        with open(f'{filler_file}', 'wb') as file:
            file.write(os.urandom(1024 * 1024))

    yield

    subprocessor.run_command(f'sudo umount {RAMDISK_PATH}')
    time.sleep(1)
    Path.rmdir(RAMDISK_PATH)
