"""Test enhanced debug mode and error handling in pypack."""

import contextlib
import logging
import tempfile
from pathlib import Path
from unittest.mock import Mock, patch

import pytest

from sfi.pypack.pypack import (
    LoaderType,
    PackageWorkflow,
    StandardCleaningStrategy,
    WorkflowConfig,
)


class TestEnhancedDebugMode:
    """Test enhanced debug mode functionality."""

    def test_debug_mode_enhanced_output(self, caplog):
        """Test that debug mode provides enhanced diagnostic information."""
        with tempfile.TemporaryDirectory() as temp_dir:
            temp_path = Path(temp_dir)

            # Create minimal pyproject.toml
            pyproject = temp_path / "pyproject.toml"
            pyproject.write_text("""
[project]
name = "test-project"
version = "1.0.0"
description = "Test project"
dependencies = []
""")

            # Mock the workflow
            with patch("sfi.pypack.pypack.Solution") as mock_solution:
                mock_solution.from_directory.return_value = Mock(projects={})

                # Enable debug logging
                caplog.set_level(logging.DEBUG)

                # Create workflow instance
                config = WorkflowConfig(
                    directory=temp_path,
                    project_name="test-project",
                    python_version="3.8.10",
                    loader_type=LoaderType.CONSOLE,
                    generate_loader=True,
                    offline=False,
                    max_concurrent=4,
                )
                workflow = PackageWorkflow(
                    root_dir=temp_path,
                    config=config,
                    cleaning_strategy=StandardCleaningStrategy(),
                )

                # Test list_projects with debug mode
                workflow.list_projects()

                # Verify enhanced debug information is present
                debug_records = [
                    record
                    for record in caplog.records
                    if record.levelno == logging.DEBUG
                ]
                debug_messages = [record.getMessage() for record in debug_records]

                # Should have debug information about the operation
                assert any("listing" in msg.lower() for msg in debug_messages)
                assert any("projects" in msg.lower() for msg in debug_messages)

    def test_error_handling_enhanced_output(self, caplog):
        """Test enhanced error handling with increased line limit."""
        with tempfile.TemporaryDirectory() as temp_dir:
            temp_path = Path(temp_dir)

            # Create dist directory for error file saving
            dist_dir = temp_path / "dist"
            dist_dir.mkdir()

            # Create workflow
            config = WorkflowConfig(directory=temp_path)
            workflow = PackageWorkflow(
                root_dir=temp_path,
                config=config,
                cleaning_strategy=StandardCleaningStrategy(),
            )

            # Create a mock result with lots of error lines
            mock_result = Mock()
            mock_result.stderr = "\n".join([
                f"Error line {i}" for i in range(60)
            ])  # 60 lines of errors
            mock_result.returncode = 1

            mock_exe_path = temp_path / "test.exe"

            # Enable error logging
            caplog.set_level(logging.ERROR)

            # Test error handling
            workflow._handle_execution_error(mock_exe_path, mock_result)

            error_records = [
                record for record in caplog.records if record.levelno == logging.ERROR
            ]
            error_messages = [record.getMessage() for record in error_records]

            # Should show more lines (50 instead of 20)
            error_detail_lines = [
                msg for msg in error_messages if msg.startswith("  Error line")
            ]
            assert len(error_detail_lines) >= 50  # Should show at least 50 lines

            # Should indicate more lines are available
            assert any("还有" in msg and "行错误信息" in msg for msg in error_messages)

            # Should mention saving to file
            assert any("完整错误信息已保存到" in msg for msg in error_messages)


class TestEnhancedBuildLogging:
    """Test enhanced build logging functionality."""

    @patch("sfi.pypack.pypack.Solution")
    @patch("sfi.pypack.pypack.asyncio.run")
    def test_build_debug_summary(self, mock_asyncio_run, mock_solution, caplog):
        """Test that build command shows enhanced debug summary."""
        with tempfile.TemporaryDirectory() as temp_dir:
            temp_path = Path(temp_dir)

            # Create minimal pyproject.toml
            pyproject = temp_path / "pyproject.toml"
            pyproject.write_text("""
[project]
name = "test-project"
version = "1.0.0"
description = "Test project"
dependencies = []
""")

            mock_solution.from_directory.return_value = Mock(
                projects={"test-project": Mock()}
            )
            mock_asyncio_run.return_value = None

            # Enable debug logging
            caplog.set_level(logging.DEBUG)

            import sys

            from sfi.pypack.pypack import main

            # Mock command line arguments for build with debug
            with patch.object(
                sys, "argv", ["pypack", "build", "--debug"]
            ), contextlib.suppress(SystemExit):
                main()

            # Verify enhanced debug information
            debug_records = [
                record for record in caplog.records if record.levelno == logging.DEBUG
            ]
            debug_messages = [record.getMessage() for record in debug_records]

            # Should have build summary information
            assert any("BUILD SUMMARY" in msg for msg in debug_messages)
            assert any("Root directory" in msg for msg in debug_messages)
            assert any("Python version" in msg for msg in debug_messages)
            assert any("Loader type" in msg for msg in debug_messages)


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