import pytest

from keble_helpers.ai.agent import AgenticActionPayload, AgenticActionWarningLevel


def test_extract_agentic_action_payload_returns_none_when_missing():
    assert AgenticActionPayload.extract_agentic_action_payload({"foo": "bar"}) is None
    assert AgenticActionPayload.extract_agentic_action_payload([{"foo": "bar"}]) is None
    assert (
        AgenticActionPayload.extract_agentic_action_payload(
            {"object": "not_agentic_action_payload", "message": "x", "warning_level": "SAFE"}
        )
        is None
    )


def test_extract_agentic_action_payload_root_dict():
    payload = AgenticActionPayload.extract_agentic_action_payload(
        {"object": "agentic_action_payload", "message": "hello", "warning_level": "SAFE"}
    )

    assert payload is not None
    assert payload.object == "agentic_action_payload"
    assert payload.message == "hello"
    assert payload.warning_level == AgenticActionWarningLevel.SAFE


def test_extract_agentic_action_payload_accepts_warningLevel():
    payload = AgenticActionPayload.extract_agentic_action_payload(
        {"object": "agentic_action_payload", "message": "hello", "warningLevel": "SAFE"}
    )

    assert payload is not None
    assert payload.warning_level == AgenticActionWarningLevel.SAFE


def test_extract_agentic_action_payload_searches_nested_structures():
    args = {
        "tool": "demo",
        "input": [
            {"noop": True},
            {
                "data": {
                    "object": "agentic_action_payload",
                    "message": "nested",
                    "warning_level": "MUTATION",
                }
            },
        ],
    }
    payload = AgenticActionPayload.extract_agentic_action_payload(args)

    assert payload is not None
    assert payload.message == "nested"
    assert payload.warning_level == AgenticActionWarningLevel.MUTATION


def test_extract_agentic_action_payload_raises_when_object_matches_but_invalid():
    with pytest.raises(ValueError, match=r"missing 'message' field"):
        AgenticActionPayload.extract_agentic_action_payload(
            {"object": "agentic_action_payload", "warning_level": "SAFE"}
        )

    with pytest.raises(ValueError, match=r"missing 'warning_level'/'warningLevel' field"):
        AgenticActionPayload.extract_agentic_action_payload(
            {"object": "agentic_action_payload", "message": "hello"}
        )
