"""Tests for deterministic local workshop tools."""

from __future__ import annotations

from src.tools import (
    LANGCHAIN_TOOLS,
    create_escalation,
    get_account_status,
    get_order_status,
    get_policy,
    normalize_tool_payload,
    search_kb,
)


def test_search_kb_finds_refund_article() -> None:
    """Return a matching article for refund-related queries."""
    result = search_kb("How long do refunds take?")

    assert result["ok"] is True
    assert result["payload"]["article"]["id"] == "kb-001"


def test_get_policy_returns_not_found_payload() -> None:
    """Return a structured not-found payload for unknown policies."""
    result = get_policy("missing_policy")

    assert result["ok"] is False
    assert result["payload"]["policy"] is None


def test_order_and_account_lookup_are_structured() -> None:
    """Lookups should return structured payloads for valid IDs."""
    order = get_order_status("2345")
    account = get_account_status("A-102")

    assert order["payload"]["order"]["status"] == "shipped"
    assert account["payload"]["account"]["status"] == "locked"


def test_create_escalation_is_deterministic() -> None:
    """Create stable escalation identifiers for live demos."""
    result = create_escalation("T-123", "Duplicate charge")

    assert result["payload"]["escalation_id"] == "ESC-T-123"
    assert result["payload"]["status"] == "created"


def test_normalize_tool_payload_simplifies_output() -> None:
    """Normalize raw tool output for notebook display."""
    normalized = normalize_tool_payload(get_policy("refund_policy"))

    assert normalized["tool"] == "get_policy"
    assert normalized["ok"] is True


def test_langchain_tool_wrappers_delegate_to_local_tools() -> None:
    """Expose the same deterministic payloads through LangChain tools."""
    tools_by_name = {tool_.name: tool_ for tool_ in LANGCHAIN_TOOLS}

    assert tools_by_name["search_kb"].invoke({"query": "refund"})["tool_name"] == "search_kb"
    assert (
        tools_by_name["get_policy"].invoke({"policy_name": "refund_policy"})["tool_name"]
        == "get_policy"
    )
    assert (
        tools_by_name["get_order_status"].invoke({"order_id": "1234"})["tool_name"]
        == "get_order_status"
    )
    assert (
        tools_by_name["get_account_status"].invoke({"account_id": "A-101"})["tool_name"]
        == "get_account_status"
    )
    assert (
        tools_by_name["create_escalation"].invoke(
            {"ticket_id": "T-9", "reason": "risk"}
        )["tool_name"]
        == "create_escalation"
    )


def test_tool_docstrings_are_instructional() -> None:
    """Keep tool docstrings explicit so they help model tool selection."""
    assert "Use this tool when" in search_kb.__doc__
    assert "Use this tool when" in get_policy.__doc__
    assert "Use this tool when" in get_order_status.__doc__
    assert "Use this tool when" in get_account_status.__doc__
    assert "Use this tool when" in create_escalation.__doc__
