#!/usr/bin/python3
"""Tests for slpkg/clean_system.py using pytest."""

from unittest.mock import MagicMock, patch
import pytest
from slpkg.clean_system import CleanSystem

@pytest.fixture
def mock_config():
    with patch("slpkg.clean_system.config_load") as mock:
        mock.cyan = ""
        mock.endc = ""
        mock.red = ""
        yield mock

@pytest.fixture
def clean_system_inst(mock_config):
    with patch("slpkg.clean_system.Repositories"), \
         patch("slpkg.clean_system.Utilities"), \
         patch("slpkg.clean_system.LoadData") as mock_loader_cls:
        
        # Mock loader.load("*") to return flattened data
        mock_loader = mock_loader_cls.return_value
        mock_loader.load.return_value = {
            "slack": {"pkg1": {}, "pkg2": {}},
            "sbo": {"sbo_pkg": {}}
        }
        
        inst = CleanSystem({"option_quiet": False})
        return inst

def test_find_foreign_packages(clean_system_inst):
    # repo packages: {pkg1, pkg2, sbo_pkg}
    # installed packages: pkg1-1.0, foreign-1.0
    clean_system_inst.utils.all_installed.return_value = {
        "pkg1": "pkg1-1.0",
        "foreign": "foreign-1.0"
    }
    clean_system_inst.utils.split_package.side_effect = lambda x: {"name": x.split("-")[0]}
    
    foreign = clean_system_inst.find_foreign_packages()
    assert foreign == ["foreign-1.0"]
    assert "pkg1-1.0" not in foreign

def test_run_no_foreign(clean_system_inst, capsys):
    clean_system_inst.find_foreign_packages = MagicMock(return_value=[])
    clean_system_inst.run()
    captured = capsys.readouterr()
    assert "No foreign packages found" in captured.out

def test_run_with_foreign_no_autoremove(clean_system_inst, capsys):
    clean_system_inst.find_foreign_packages = MagicMock(return_value=["foreign-1.0"])
    clean_system_inst.run()
    captured = capsys.readouterr()
    assert "Foreign packages found" in captured.out
    assert "foreign-1.0" in captured.out
    assert "Use '--autoremove'" in captured.out

def test_run_with_foreign_autoremove(clean_system_inst):
    clean_system_inst.options["option_autoremove"] = True
    clean_system_inst.find_foreign_packages = MagicMock(return_value=["foreign-1.0"])
    # Ensure split_package returns all expected keys
    clean_system_inst.utils.split_package.return_value = {
        "name": "foreign",
        "version": "1.0",
        "arch": "x86_64",
        "build": "1",
        "tag": "SBo"
    }
    
    with patch("slpkg.clean_system.RemovePackages") as mock_remove_cls:
        clean_system_inst.run()
        # Verify that RemovePackages was initialized with the correct package names
        mock_remove_cls.assert_called_once_with(["foreign"], clean_system_inst.options)
        # Verify that remove() was called without arguments
        mock_remove_cls.return_value.remove.assert_called_once_with()
