"""
STORY-004: 實作日誌分析節點

Tests for log_node implementation.
"""

import os
from unittest.mock import patch

from fwauto.state import FirmwareState


class TestStory004LogAnalysisNode:
    """
    STORY-004: 實作日誌分析節點

    As a 系統開發者
    I want to 建立 log_node 來執行實際的日誌分析
    So that 系統能使用 Claude Code SDK 和 prompt template 分析日誌並回傳結果
    """

    def test_log_node_exists(self):
        """
        測試 log_node 函數存在

        Given: nodes/log_analysis.py 模組
        When: 我嘗試 import log_node
        Then: 應該成功 import
        """
        from src.fwauto.nodes.log import log_node

        assert callable(log_node), "log_node should be a callable function"

    def test_log_node_has_correct_signature(self):
        """
        測試 log_node 有正確的函數簽名

        Given: log_node 已定義
        When: 我檢查函數簽名
        Then: 應該接受 FirmwareState 並返回 dict
        """
        import inspect

        from src.fwauto.nodes.log import log_node

        sig = inspect.signature(log_node)
        params = list(sig.parameters.keys())

        assert "state" in params, "Should have 'state' parameter"

    def test_log_node_returns_dict(self):
        """
        測試 log_node 返回字典

        Given: 有效的 FirmwareState
        When: 調用 log_node
        Then: 應該返回包含結果的字典
        """
        from src.fwauto.nodes.log import log_node

        # 創建測試 state
        test_state: FirmwareState = {
            "user_prompt": "測試分析",
            "project_root": os.getcwd(),
            "project_initialized": True,
            "build_status": "pending",
            "build_errors": [],
            "build_log": "",
            "flash_status": "pending",
            "flash_errors": [],
            "flash_log": "",
            "iteration": 0,
            "max_retries": 3,
            "execution_mode": "log",
            "command": "log-analysis",
            "command_args": {"analysis_prompt": "測試分析"},
            "mode_metadata": None,
            "command_error": None,
            "log_file_path": "prompts/log.md",  # 使用存在的檔案測試
            "log_analysis_result": None,
            "firmware_path": None,
            "platform": "test",
        }

        # Mock claude_code_sdk query function
        with patch("src.fwauto.nodes.log.query") as mock_query:
            # 設置 mock 返回一個 async generator
            async def mock_response():
                yield "測試回應"

            mock_query.return_value = mock_response()

            result = log_node(test_state)

            assert isinstance(result, dict), "Should return a dict"
            assert "log_analysis_result" in result, "Should update log_analysis_result"
