"""Tests for chat node."""

from unittest.mock import patch

import pytest

from src.fwauto.nodes.chat import chat_node
from src.fwauto.state import FirmwareState


@pytest.fixture
def mock_state() -> FirmwareState:
    """Create mock firmware state."""
    return {
        "user_prompt": "chat",
        "project_root": "/test/project",
        "project_initialized": True,
        "build_status": "pending",
        "build_errors": [],
        "build_log": "",
        "flash_status": "pending",
        "flash_errors": [],
        "flash_log": "",
        "iteration": 0,
        "max_retries": 3,
        "execution_mode": "chat",
        "command": "chat",
        "command_args": {},
        "mode_metadata": None,
        "command_error": None,
        "log_file_path": None,
        "log_analysis_result": None,
        "firmware_path": None,
        "platform": "stm32_keil",
    }


@patch("src.fwauto.nodes.chat.prompt_manager")
@patch("threading.Thread")
def test_chat_node_loads_prompt(mock_thread, mock_prompt_manager, mock_state):
    """Test that chat_node loads the chat prompt template."""
    # Setup
    mock_prompt_manager.get_prompt.return_value = "Test prompt"

    # Mock thread execution - simulate successful execution
    mock_thread_instance = mock_thread.return_value
    mock_thread_instance.start.return_value = None
    mock_thread_instance.join.return_value = None

    # Execute
    result = chat_node(mock_state)

    # Verify
    mock_prompt_manager.get_prompt.assert_called_once_with("chat", dict(mock_state))
    assert result.get("chat_completed") is True
    mock_thread.assert_called_once()
    mock_thread_instance.start.assert_called_once()
    mock_thread_instance.join.assert_called_once()


@patch("src.fwauto.nodes.chat.prompt_manager")
def test_chat_node_handles_prompt_error(mock_prompt_manager, mock_state):
    """Test that chat_node handles prompt loading errors."""
    # Setup
    mock_prompt_manager.get_prompt.side_effect = Exception("Prompt not found")

    # Execute
    result = chat_node(mock_state)

    # Verify
    assert result.get("chat_completed") is False
