"""Unit tests for system utilities."""

import os
import tempfile
from datetime import datetime, timedelta
from pathlib import Path

from src.server.utils.system import (
    DiskInfo,
    ProcessInfo,
    SystemUtilities,
    get_system_utilities,
)


def test_system_utilities_initialization():
    """Test system utilities initialization."""
    utils = SystemUtilities()
    assert utils is not None


def test_get_disk_usage():
    """Test getting disk usage information."""
    utils = SystemUtilities()
    disk_info = utils.get_disk_usage("/")

    assert disk_info is not None
    assert isinstance(disk_info, DiskInfo)
    assert disk_info.total_bytes > 0
    assert disk_info.free_bytes >= 0
    assert disk_info.percent_used >= 0


def test_get_all_disk_usage():
    """Test getting disk usage for all partitions."""
    utils = SystemUtilities()
    disk_infos = utils.get_all_disk_usage()

    assert isinstance(disk_infos, list)
    # Should have at least one partition
    assert len(disk_infos) >= 0


def test_cleanup_directory():
    """Test directory cleanup."""
    utils = SystemUtilities()

    with tempfile.TemporaryDirectory() as tmpdir:
        # Create some test files
        old_time = (datetime.now() - timedelta(days=31)).timestamp()

        for i in range(3):
            file_path = Path(tmpdir) / f"old_file_{i}.txt"
            file_path.write_text(f"old file {i}")
            Path(file_path).touch()
            os.utime(file_path, (old_time, old_time))

        for i in range(2):
            file_path = Path(tmpdir) / f"new_file_{i}.txt"
            file_path.write_text(f"new file {i}")

        # Clean up files older than 30 days
        deleted = utils.cleanup_directory(tmpdir, "*.txt", max_age_days=30)

        assert deleted == 3


def test_cleanup_empty_directories():
    """Test empty directory cleanup."""
    utils = SystemUtilities()

    with tempfile.TemporaryDirectory() as tmpdir:
        # Create nested directories
        (Path(tmpdir) / "dir1").mkdir()
        (Path(tmpdir) / "dir2").mkdir()
        (Path(tmpdir) / "dir2" / "subdir").mkdir()

        # Create a file in one directory
        (Path(tmpdir) / "dir1" / "file.txt").write_text("content")

        # Clean up empty directories
        deleted = utils.cleanup_empty_directories(tmpdir)

        assert deleted >= 1


def test_get_directory_size():
    """Test getting directory size."""
    utils = SystemUtilities()

    with tempfile.TemporaryDirectory() as tmpdir:
        # Create test files
        (Path(tmpdir) / "file1.txt").write_text("a" * 1000)
        (Path(tmpdir) / "file2.txt").write_text("b" * 2000)

        size = utils.get_directory_size(tmpdir)

        assert size >= 3000  # At least 3000 bytes


def test_get_directory_size_nonexistent():
    """Test getting directory size for non-existent directory."""
    utils = SystemUtilities()
    size = utils.get_directory_size("/nonexistent/path")
    assert size == 0


def test_get_process_info():
    """Test getting process information."""
    import os

    utils = SystemUtilities()
    pid = os.getpid()

    proc_info = utils.get_process_info(pid)

    assert proc_info is not None
    assert isinstance(proc_info, ProcessInfo)
    assert proc_info.pid == pid
    assert proc_info.name is not None
    assert proc_info.cpu_percent >= 0
    assert proc_info.memory_percent >= 0


def test_get_process_info_current():
    """Test getting current process information."""
    utils = SystemUtilities()
    proc_info = utils.get_process_info()

    assert proc_info is not None
    assert proc_info.pid > 0


def test_get_process_info_invalid():
    """Test getting process info for invalid PID."""
    utils = SystemUtilities()
    proc_info = utils.get_process_info(99999999)

    assert proc_info is None


def test_get_all_processes():
    """Test getting information about all processes."""
    utils = SystemUtilities()
    processes = utils.get_all_processes()

    assert isinstance(processes, list)
    # Should have at least some processes
    assert len(processes) > 0


def test_get_system_info():
    """Test getting system information."""
    utils = SystemUtilities()
    system_info = utils.get_system_info()

    assert system_info is not None
    assert "platform" in system_info
    assert "cpu_count" in system_info
    assert "hostname" in system_info
    assert "python_version" in system_info


def test_get_network_info():
    """Test getting network information."""
    utils = SystemUtilities()
    net_info = utils.get_network_info()

    assert net_info is not None
    assert "bytes_sent" in net_info
    assert "bytes_recv" in net_info
    assert net_info["bytes_sent"] >= 0
    assert net_info["bytes_recv"] >= 0


def test_copy_file_atomic():
    """Test atomic file copy."""
    utils = SystemUtilities()

    with tempfile.TemporaryDirectory() as tmpdir:
        src_file = Path(tmpdir) / "source.txt"
        dest_file = Path(tmpdir) / "dest.txt"

        src_file.write_text("test content")

        result = utils.copy_file_atomic(str(src_file), str(dest_file))

        assert result is True
        assert dest_file.exists()
        assert dest_file.read_text() == "test content"


def test_copy_file_atomic_nonexistent():
    """Test atomic file copy with non-existent source."""
    utils = SystemUtilities()

    result = utils.copy_file_atomic(
        "/nonexistent/source.txt", "/tmp/dest.txt"
    )

    assert result is False


def test_get_system_utilities_singleton():
    """Test singleton system utilities."""
    utils1 = get_system_utilities()
    utils2 = get_system_utilities()

    assert utils1 is utils2
    assert isinstance(utils1, SystemUtilities)

