#!/usr/bin/env python3
"""
Test for pypack GUI logging functionality.
"""

import sys
from pathlib import Path

import pytest
from PySide2.QtWidgets import QApplication

from sfi.pypack.pypack import WorkflowConfig
from sfi.pypack.pypack_gui import BuildWorker, PypackGUI

# Add project root to path
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))


class TestPypackGUILogging:
    """Test pypack GUI logging functionality."""

    @pytest.fixture(scope="class")
    def app(self):
        """Create QApplication instance."""
        app = QApplication.instance()
        if app is None:
            app = QApplication([])
        return app

    def test_build_worker_logging_capture(self, app, tmp_path):
        """Test that BuildWorker properly captures logging output."""
        # Create a simple test config
        config = WorkflowConfig(
            directory=tmp_path,
            project_name="test_project",
            python_version="3.8.10",
            loader_type="console",
            generate_loader=False,
            offline=True,
            max_concurrent=1,
            debug=True,
        )

        # Create worker
        worker = BuildWorker(config)

        # Collect log messages
        log_messages = []

        def collect_log(msg):
            log_messages.append(msg)

        # Connect signal to our collector
        worker.log_signal.connect(collect_log)

        # Run worker (this will fail since there's no actual project, but logging should still work)
        worker.run()

        # Check that we received some log messages
        # Note: Even failed builds should produce some logging output
        assert len(log_messages) > 0, "Should have captured some log messages"

        # Check that log messages are not empty
        assert any(msg for msg in log_messages if msg.strip()), (
            "Should have non-empty log messages"
        )

    def test_gui_log_display_integration(self, app):
        """Test that GUI log widget integrates properly with build process."""
        # Create GUI instance
        gui = PypackGUI()

        # Check that log widget exists and has append_log method
        assert hasattr(gui, "log_widget"), "GUI should have log_widget"
        assert hasattr(gui.log_widget, "append_log"), (
            "Log widget should have append_log method"
        )

        # Test appending a log message
        test_message = "Test log message"
        gui.log_widget.append_log(test_message)

        # Check that the message was added to the text area (check info tab)
        log_content = gui.log_widget.info_text.toPlainText()
        assert test_message in log_content, "Log message should appear in log display"

        # Clean up
        gui.close()


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
