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

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

import pytest
from slpkg.import_packages import ImportPackages


@pytest.fixture
def mock_config():
    """Mock config_load for ImportPackages."""
    with patch("slpkg.import_packages.config_load") as mock:
        mock.cyan = ""
        mock.red = ""
        mock.yellow = ""
        mock.endc = ""
        mock.bold = ""
        yield mock


@pytest.fixture
def import_inst(mock_config):
    """Fixture for ImportPackages instance with mocked dependencies."""
    with patch("slpkg.import_packages.Utilities"), \
         patch("slpkg.import_packages.Repositories"), \
         patch("slpkg.import_packages.View"):
        inst = ImportPackages({"option_quiet": False})
        return inst


def test_parse_file(import_inst, tmp_path):
    """Test parsing a .pkgs file with repo headers."""
    pkgs_file = tmp_path / "test.pkgs"
    content = "# [sbo]\npkg1\n# deps: dep1\npkg2\n# [_alien]\npkgA\n"
    pkgs_file.write_text(content)
    
    grouped = import_inst._parse_file(pkgs_file)
    
    assert "sbo" in grouped
    assert "pkg1" in grouped["sbo"]
    assert "pkg2" in grouped["sbo"]
    assert "_alien" in grouped
    assert "pkgA" in grouped["_alien"]


def test_validate_packages(import_inst):
    """Test package validation and repo mapping."""
    grouped = {
        "sbo": ["pkg1"],
        "_alien": ["pkgA", "missing"]
    }
    all_repos_data = {
        "sbo": {"pkg1": {}},
        "alien": {"pkgA": {}}
    }
    
    results = import_inst._validate_packages(grouped, all_repos_data)
    
    # pkg1 found in sbo
    # pkgA found in alien (mapped from _alien)
    # missing not found
    assert "pkg1" in results["to_install"]["sbo"]
    assert "pkgA" in results["to_install"]["alien"]
    assert "missing" in results["missing"]


def test_run_import_success(import_inst, tmp_path):
    """Test the full run process."""
    pkgs_file = tmp_path / "test.pkgs"
    pkgs_file.write_text("# [sbo]\npkg1\n")
    
    mock_all_data = {"sbo": {"pkg1": {}}}
    
    with patch("slpkg.import_packages.LoadData") as mock_loader_cls:
        mock_loader_cls.return_value.load.return_value = mock_all_data
        
        plan = import_inst.run(str(pkgs_file))
        
        assert len(plan) == 1
        assert plan[0][0] == "sbo"
        assert plan[0][1] == ["pkg1"]
        import_inst.view.question.assert_called_once()
