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

from pathlib import Path
from unittest.mock import MagicMock, patch

import pytest
from slpkg.export import Export


@pytest.fixture
def mock_config():
    """Mock config_load for Export."""
    with patch("slpkg.export.config_load") as mock:
        mock.cyan = ""
        mock.red = ""
        mock.endc = ""
        mock.deps_log_file = Path("/tmp/deps.log")
        yield mock


@pytest.fixture
def export_inst(mock_config):
    """Fixture for Export instance with mocked dependencies."""
    with patch("slpkg.export.Utilities"), \
         patch("slpkg.export.Mark"):
        inst = Export({"option_quiet": False})
        return inst


def test_get_manually_installed(export_inst):
    """Test determining manually installed packages."""
    # Mock marks.log
    export_inst.mark._read_marks_log.return_value = {"pkg1", "marked_pkg"}
    
    # Mock all installed packages
    export_inst.utils.all_installed.return_value = {
        "pkg1": "pkg1-1.0",
        "marked_pkg": "marked_pkg-1.0",
        "dep_pkg": "dep_pkg-1.0",
        "top_pkg": "top_pkg-1.0"
    }
    
    # Mock deps.log
    # top_pkg is not a dependency of anyone
    # dep_pkg is a dependency of top_pkg
    deps_data = {
        "top_pkg": ["dep_pkg"],
        "dep_pkg": []
    }
    export_inst.utils.read_json_file.return_value = deps_data
    
    final_list = export_inst._get_manually_installed()
    
    # Should include: pkg1, marked_pkg, top_pkg
    # Should NOT include: dep_pkg (since it's a dependency)
    assert "pkg1" in final_list
    assert "marked_pkg" in final_list
    assert "top_pkg" in final_list
    assert "dep_pkg" not in final_list


def test_run_export_success(export_inst, tmp_path):
    """Test successful export to a file."""
    export_list = ["pkg1", "pkg2"]
    export_inst._get_manually_installed = MagicMock(return_value=export_list)
    
    output_file = tmp_path / "test.pkgs"
    export_inst.run(str(output_file))
    
    assert output_file.exists()
    content = output_file.read_text()
    assert "pkg1" in content
    assert "pkg2" in content


def test_run_export_no_packages(export_inst, capsys):
    """Test export when no packages are found."""
    export_inst._get_manually_installed = MagicMock(return_value=[])
    
    export_inst.run("test.pkgs")
    captured = capsys.readouterr()
    assert "No manually installed packages found" in captured.out
