"""Tests for cross-platform compatibility helpers."""

from __future__ import annotations

import sys


class TestFileLocking:
    def test_lock_unlock_unix(self, tmp_path):
        """On non-Windows, lock_file / unlock_file use fcntl."""
        if sys.platform == "win32":
            # Skip on actual Windows — tested by test_lock_unlock_windows
            return

        from ilum.compat import lock_file, unlock_file

        f = (tmp_path / "test.lock").open("w")
        try:
            lock_file(f)
            unlock_file(f)
        finally:
            f.close()

    def test_lock_unlock_windows(self, tmp_path):
        """On Windows, lock_file / unlock_file use msvcrt."""
        if sys.platform != "win32":
            # Skip on Unix — tested by test_lock_unlock_unix
            return

        from ilum.compat import lock_file, unlock_file

        f = (tmp_path / "test.lock").open("w")
        try:
            lock_file(f)
            unlock_file(f)
        finally:
            f.close()

    def test_manager_save_uses_atomic_write(self, tmp_config_dir):
        """ConfigManager.save() uses atomic write (tempfile + os.replace)."""
        from ilum.config.manager import ConfigManager
        from ilum.config.models import IlumConfig

        mgr = ConfigManager(tmp_config_dir)
        config = IlumConfig(active_profile="atomic-test")

        # Save should work (atomic write with tempfile + os.replace)
        mgr.save(config)

        # Verify the file was written correctly
        loaded = mgr.load()
        assert loaded.active_profile == "atomic-test"

        # No leftover temp files in the config directory
        tmp_files = list(mgr.config_file.parent.glob("*.tmp"))
        assert len(tmp_files) == 0

    def test_compat_module_importable(self):
        """The compat module can be imported on any platform."""
        import ilum.compat

        assert callable(ilum.compat.lock_file)
        assert callable(ilum.compat.unlock_file)
