"""Tests for CommandLogger."""


import pytest

from fwauto.command_logger import CommandLogger


@pytest.fixture
def mock_state():
    """Mock FirmwareState for testing."""
    return {"platform": "am62x", "project_root": "/test/project"}


class TestCommandLogger:
    """Test CommandLogger functionality."""

    def test_initialization(self, tmp_path, mock_state):
        """Test CommandLogger initialization."""
        logger = CommandLogger(tmp_path, mock_state)

        assert logger.log_file.exists()
        assert logger.command_count == 0
        assert logger.project_root == tmp_path

        # Check header content
        content = logger.log_file.read_text(encoding="utf-8")
        assert "Command Execution Log" in content
        assert str(tmp_path) in content
        assert "Platform: am62x" in content

    def test_log_command_execution(self, tmp_path, mock_state):
        """Test logging a command execution."""
        logger = CommandLogger(tmp_path, mock_state)

        logger.log_command_execution(
            command="/deploy --binary-args test.hex",
            parameters={"binary_args": "test.hex"},
            status="success",
            output="✅ Deploy successful",
        )

        content = logger.log_file.read_text(encoding="utf-8")
        assert "/deploy --binary-args test.hex" in content
        assert "binary_args: test.hex" in content
        assert "Status: success" in content
        assert "✅ Deploy successful" in content
        assert logger.command_count == 1

    def test_log_command_without_parameters(self, tmp_path, mock_state):
        """Test logging a command without parameters."""
        logger = CommandLogger(tmp_path, mock_state)

        logger.log_command_execution(
            command="/build", parameters={}, status="error", output="Build failed"
        )

        content = logger.log_file.read_text(encoding="utf-8")
        assert "/build" in content
        assert "Parameters: (none)" in content
        assert "Status: error" in content
        assert "Build failed" in content

    def test_multiple_commands(self, tmp_path, mock_state):
        """Test logging multiple commands."""
        logger = CommandLogger(tmp_path, mock_state)

        logger.log_command_execution(
            command="/build", parameters={}, status="success", output="Build OK"
        )
        logger.log_command_execution(
            command="/deploy --binary-args on",
            parameters={"binary_args": "on"},
            status="success",
            output="Deploy OK",
        )
        logger.log_command_execution(
            command="/log uart.log",
            parameters={"log_path": "uart.log", "analysis_prompt": "分析這份 log"},
            status="success",
            output="Analysis complete",
        )

        content = logger.log_file.read_text(encoding="utf-8")
        assert "/build" in content
        assert "/deploy" in content
        assert "/log" in content
        assert logger.command_count == 3

    def test_finalize(self, tmp_path, mock_state):
        """Test session finalization."""
        logger = CommandLogger(tmp_path, mock_state)
        logger.command_count = 5

        logger.finalize()

        content = logger.log_file.read_text(encoding="utf-8")
        assert "Total commands: 5" in content
        assert "Session ended:" in content
        assert "Duration:" in content

    def test_cjk_content(self, tmp_path, mock_state):
        """Test logging with CJK characters."""
        logger = CommandLogger(tmp_path, mock_state)

        logger.log_command_execution(
            command="/log uart.log '有任何 error 嗎?'",
            parameters={"log_path": "uart.log", "analysis_prompt": "有任何 error 嗎?"},
            status="success",
            output="分析結果：沒有發現 error",
        )

        content = logger.log_file.read_text(encoding="utf-8")
        assert "有任何 error 嗎?" in content
        assert "分析結果：沒有發現 error" in content

    def test_log_directory_creation(self, tmp_path, mock_state):
        """Test that log directory is created if it doesn't exist."""
        # Remove .fwauto/logs if it exists
        log_dir = tmp_path / ".fwauto" / "logs"
        if log_dir.exists():
            import shutil

            shutil.rmtree(log_dir)

        logger = CommandLogger(tmp_path, mock_state)

        assert log_dir.exists()
        assert logger.log_file.exists()
