"""Tests for tool exception handling and summarizer YAML parsing robustness."""

import yaml

from kiss.core.kiss_agent import KISSAgent
from kiss.core.relentless_agent import finish


def _make_agent() -> KISSAgent:
    agent = KISSAgent("Test")
    agent._reset(
        model_name="claude-haiku-4-5",
        is_agentic=True,
        max_steps=5,
        max_budget=0.01,
        model_config=None,
    )
    return agent


def test_keyboard_interrupt_propagates() -> None:
    def interrupt_tool(x: str) -> str:
        """Tool that raises KeyboardInterrupt.

        Args:
            x: Input.
        """
        raise KeyboardInterrupt()

    agent = _make_agent()
    agent._add_functions([finish, interrupt_tool])
    caught = False
    try:
        agent._execute_tool({"name": "interrupt_tool", "arguments": {"x": "a"}})
    except KeyboardInterrupt:
        caught = True
    assert caught, "KeyboardInterrupt should propagate"


def _parse_summarizer_result(summarizer_result: str) -> str:
    """Replicate the summarizer YAML parsing logic from relentless_agent.perform_task."""
    try:
        parsed = yaml.safe_load(summarizer_result)
        return (
            parsed.get("result", summarizer_result)
            if isinstance(parsed, dict)
            else summarizer_result
        )
    except Exception:
        return summarizer_result


def test_summarizer_yaml_invalid_yaml() -> None:
    raw = (
        "The `_execute_tool` method in `/Users/ksen/work/kiss/src/kiss/core/kiss_agent.py`\n"
        "was modified to catch BaseException instead of Exception.\n"
        "key: value\n"
        "  broken: indent"
    )
    result = _parse_summarizer_result(raw)
    assert result == raw


def test_summarizer_yaml_plain_text() -> None:
    raw = "This is just plain text summary of the work done."
    assert _parse_summarizer_result(raw) == raw


def test_summarizer_yaml_returns_scalar() -> None:
    raw = "42"
    result = _parse_summarizer_result(raw)
    assert result == raw

