"""
STORY-006: 錯誤處理與使用者體驗優化

Tests for error handling and UX improvements in log analysis.
"""

import os
from unittest.mock import patch

from fwauto.nodes.log import log_node
from fwauto.state import FirmwareState


class TestStory006ErrorHandlingAndUX:
    """
    STORY-006: 錯誤處理與使用者體驗優化

    As a 韌體開發者
    I want to 得到清晰的錯誤訊息和分析結果展示
    So that 我能快速理解分析狀況並處理可能的問題
    """

    # AC-01: 檔案檢查與錯誤提示
    def test_handles_missing_user_prompt(self):
        """
        測試處理缺少 user_prompt 的情況

        Given: FirmwareState 沒有提供 user_prompt
        When: 調用 log_node
        Then: 應該返回錯誤訊息
        """
        test_state: FirmwareState = {
            "user_prompt": "",  # Empty 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": None,
            "mode_metadata": None,
            "command_error": None,
            "log_file_path": "logs/uart.log",
            "log_analysis_result": None,
        }

        result = log_node(test_state)

        assert "log_analysis_result" in result
        assert "Error" in result["log_analysis_result"] or "error" in result["log_analysis_result"].lower()

    # AC-02 & AC-03: 分析結果展示和日誌記錄
    def test_returns_analysis_result_in_state(self, tmp_path):
        """
        測試返回分析結果到 state

        Given: 有效的分析請求
        When: 調用 log_node
        Then: 應該在 state 中包含 log_analysis_result
        """
        # Create a temporary log file
        log_file = tmp_path / "uart.log"
        log_file.write_text("Test log content\nLine 2\nLine 3")

        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": str(log_file),
            "log_analysis_result": None,
        }

        # Mock the query function to avoid real API calls
        with patch("fwauto.nodes.log.query") as mock_query:
            # Create a proper async generator mock
            async def mock_async_generator():
                from fwauto.nodes.log import AssistantMessage, TextBlock

                # Simulate AI response
                yield AssistantMessage(
                    content=[TextBlock(text="分析完成：日誌檔案包含 3 行內容")],
                    model="claude-test",
                    parent_tool_use_id=None,
                )

            mock_query.return_value = mock_async_generator()

            result = log_node(test_state)

            assert "log_analysis_result" in result
            assert isinstance(result["log_analysis_result"], str)
            assert len(result["log_analysis_result"]) > 0

    def test_handles_prompt_loading_error(self, tmp_path):
        """
        測試處理 prompt 載入錯誤

        Given: PromptManager 無法載入 template
        When: 調用 log_node
        Then: 應該返回友善的錯誤訊息
        """
        # Create a temporary log file to pass file existence check
        log_file = tmp_path / "uart.log"
        log_file.write_text("Test log content")

        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": None,
            "mode_metadata": None,
            "command_error": None,
            "log_file_path": str(log_file),
            "log_analysis_result": None,
        }

        # Mock PromptManager to raise exception
        with patch("fwauto.nodes.log.prompt_manager") as mock_pm:
            mock_pm.get_prompt.side_effect = Exception("Template not found")

            result = log_node(test_state)

            assert "log_analysis_result" in result
            assert "Error" in result["log_analysis_result"]
            assert "prompt" in result["log_analysis_result"].lower()
