"""Tests for the agent loop: termination, budgets, trajectories, tracing.

These are the tests the course asks you to read before writing your own agent,
because each one encodes a failure mode that costs real money in production.
"""

import unittest

from agentic import (
    Agent,
    Budget,
    FakeModel,
    Message,
    Registry,
    Stop,
    Tracer,
    reset_call_ids,
    tool,
    tool_call,
    tool_calls,
)
from agentic.tools import FatalToolError, ToolConfigError, ToolError


# -- fixtures -----------------------------------------------------------

ORDERS = {"4471": {"id": "4471", "status": "delivered", "total_paise": 249900}}


@tool(description="Look up an order by its id.", order_id="The order id, digits only.")
def get_order(order_id: str) -> dict:
    if order_id not in ORDERS:
        raise ToolError(f"no order {order_id!r}")
    return ORDERS[order_id]


@tool(description="Search the help centre.", q="A short search phrase.")
def search_help(q: str) -> str:
    return f"3 articles about {q}"


@tool(
    description="Issue a refund for an order.",
    order_id="The order id.",
    mutating=True,
    requires_confirmation=True,
)
def refund(order_id: str) -> str:
    return f"refunded {order_id}"


@tool(description="A tool that always blows up internally.")
def broken() -> str:
    raise RuntimeError("upstream exploded with a secret in the message")


@tool(description="A tool that denies authorization.")
def forbidden() -> str:
    raise FatalToolError("caller may not do this")


def registry(*tools, **kw) -> Registry:
    return Registry(list(tools), **kw)


class TestHappyPath(unittest.TestCase):
    def setUp(self) -> None:
        reset_call_ids()

    def test_answers_without_tools(self):
        agent = Agent(FakeModel(["Hello."]))
        run = agent.run("hi")
        self.assertTrue(run.ok)
        self.assertIs(run.stop, Stop.ANSWERED)
        self.assertEqual(run.output, "Hello.")
        self.assertEqual(run.step_count, 1)
        self.assertEqual(run.trajectory(), [])

    def test_single_tool_then_answer(self):
        model = FakeModel([
            tool_call("get_order", {"order_id": "4471"}),
            "Order 4471 was delivered.",
        ])
        run = Agent(model, registry(get_order)).run("where is 4471")

        self.assertTrue(run.ok)
        self.assertEqual(run.step_count, 2)
        self.assertEqual(run.trajectory(), ["get_order"])
        self.assertTrue(run.used_tool("get_order"))

        # The tool result must be appended as a `tool` message, matched by id,
        # or the second model call is incoherent.
        tool_msgs = [m for m in run.messages if m.role == "tool"]
        self.assertEqual(len(tool_msgs), 1)
        self.assertIn("delivered", tool_msgs[0].content)
        self.assertIsNotNone(tool_msgs[0].tool_call_id)

    def test_parallel_tool_calls_both_run(self):
        model = FakeModel([
            tool_calls(("get_order", {"order_id": "4471"}), ("search_help", {"q": "refunds"})),
            "Done.",
        ])
        run = Agent(model, registry(get_order, search_help)).run("both please")
        self.assertEqual(sorted(run.trajectory()), ["get_order", "search_help"])
        self.assertEqual(len([m for m in run.messages if m.role == "tool"]), 2)

    def test_system_prompt_is_first_message(self):
        model = FakeModel(["ok"])
        Agent(model, system="You are terse.").run("hi")
        first = model.last_messages()[0]
        self.assertEqual(first.role, "system")
        self.assertEqual(first.content, "You are terse.")

    def test_history_is_replayed(self):
        model = FakeModel(["ok"])
        history = [
            Message(role="user", content="earlier question"),
            Message(role="assistant", content="earlier answer"),
        ]
        Agent(model).run("new question", history=history)
        contents = [m.content for m in model.last_messages()]
        self.assertEqual(contents, ["earlier question", "earlier answer", "new question"])


class TestTermination(unittest.TestCase):
    """Every way a run can end, and the guarantee that it always ends."""

    def setUp(self) -> None:
        reset_call_ids()

    def test_step_budget_stops_a_runaway_agent(self):
        # A model that only ever asks for tools would loop forever without a budget.
        model = FakeModel([lambda msgs: tool_call("search_help", {"q": f"q{len(msgs)}"})] * 50)
        run = Agent(model, registry(search_help), budget=Budget(max_steps=4)).run("go")

        self.assertFalse(run.ok)
        self.assertIs(run.stop, Stop.STEP_BUDGET)
        self.assertEqual(run.step_count, 4)
        self.assertIn("4-step limit", run.output)

    def test_repeated_identical_call_is_detected(self):
        # Same tool, same arguments, forever - stuck, not working.
        model = FakeModel([tool_call("search_help", {"q": "same"}) for _ in range(10)])
        run = Agent(
            model, registry(search_help), budget=Budget(max_steps=10, repeat_limit=2)
        ).run("go")

        self.assertIs(run.stop, Stop.REPEATED_CALL)
        # Stopped on the 3rd identical call, not after all 10 steps.
        self.assertEqual(run.step_count, 3)

    def test_differing_arguments_are_not_treated_as_repeats(self):
        model = FakeModel([
            tool_call("search_help", {"q": "a"}),
            tool_call("search_help", {"q": "b"}),
            tool_call("search_help", {"q": "c"}),
            "done",
        ])
        run = Agent(model, registry(search_help), budget=Budget(max_steps=6, repeat_limit=1)).run("go")
        self.assertIs(run.stop, Stop.ANSWERED)

    def test_token_budget_stops_the_run(self):
        model = FakeModel([lambda msgs: tool_call("search_help", {"q": "x" * 400})] * 20)
        run = Agent(
            model, registry(search_help), budget=Budget(max_steps=20, max_tokens=50)
        ).run("go")
        self.assertIs(run.stop, Stop.TOKEN_BUDGET)

    def test_cost_budget_stops_the_run(self):
        model = FakeModel([lambda msgs: tool_call("search_help", {"q": "x" * 4000})] * 20)
        budget = Budget(
            max_steps=20, max_cost=0.001, price_per_1k_input=1.0, price_per_1k_output=1.0
        )
        run = Agent(model, registry(search_help), budget=budget).run("go")
        self.assertIs(run.stop, Stop.COST_BUDGET)
        self.assertGreater(run.cost, 0)

    def test_fatal_tool_error_aborts_instead_of_looping(self):
        model = FakeModel([tool_call("forbidden", {}), "should never be reached"])
        run = Agent(model, registry(forbidden)).run("go")
        self.assertIs(run.stop, Stop.TOOL_FATAL)
        # The model was called once; it never saw the authorization failure.
        self.assertEqual(model.call_count, 1)

    def test_every_stop_reason_is_named(self):
        # No run may end in an unnamed state.
        model = FakeModel(["done"])
        run = Agent(model).run("hi")
        self.assertIsInstance(run.stop, Stop)


class TestToolErrorsAreCorrectable(unittest.TestCase):
    def setUp(self) -> None:
        reset_call_ids()

    def test_tool_error_is_returned_to_the_model_which_can_retry(self):
        model = FakeModel([
            tool_call("get_order", {"order_id": "9999"}),   # not found
            tool_call("get_order", {"order_id": "4471"}),   # corrected
            "Order 4471 was delivered.",
        ])
        run = Agent(model, registry(get_order)).run("find my order")

        self.assertTrue(run.ok)
        # Asked twice, succeeded once. The failed lookup is not in the trajectory
        # because nothing was retrieved by it.
        self.assertEqual(run.requested_tools(), ["get_order", "get_order"])
        self.assertEqual(run.trajectory(), ["get_order"])
        self.assertEqual(run.blocked_tools(), ["get_order"])

        first_result = run.steps[0].tool_results[0]
        self.assertFalse(first_result.ok)
        self.assertIn("no order", first_result.content)
        # The error text reached the model, which is what let it self-correct.
        self.assertIn("no order", run.messages[2].content)

    def test_bad_argument_type_is_rejected_before_the_tool_runs(self):
        model = FakeModel([tool_call("get_order", {"order_id": 4471}), "gave up"])
        run = Agent(model, registry(get_order)).run("go")
        result = run.steps[0].tool_results[0]
        self.assertFalse(result.ok)
        self.assertIn("must be str", result.content)

    def test_unknown_argument_is_rejected(self):
        model = FakeModel([
            tool_call("get_order", {"order_id": "4471", "sneaky": "x"}),
            "gave up",
        ])
        run = Agent(model, registry(get_order)).run("go")
        self.assertIn("unknown argument", run.steps[0].tool_results[0].content)

    def test_missing_required_argument_is_rejected(self):
        model = FakeModel([tool_call("get_order", {}), "gave up"])
        run = Agent(model, registry(get_order)).run("go")
        self.assertIn("missing required argument", run.steps[0].tool_results[0].content)

    def test_internal_exception_does_not_leak_details_to_the_model(self):
        model = FakeModel([tool_call("broken", {}), "gave up"])
        run = Agent(model, registry(broken)).run("go")
        content = run.steps[0].tool_results[0].content
        self.assertIn("failed internally", content)
        self.assertNotIn("secret", content)

    def test_unknown_tool_does_not_reveal_hidden_tools(self):
        model = FakeModel([tool_call("refund", {"order_id": "4471"}), "gave up"])
        # refund exists but is not in the allowlist for this context.
        reg = registry(get_order, refund, allowed={"get_order"})
        run = Agent(model, reg).run("refund it")
        content = run.steps[0].tool_results[0].content
        self.assertIn("no such tool", content)
        self.assertIn("get_order", content)
        self.assertNotIn("refund", content.split("Available:")[1])


class TestConfirmationGate(unittest.TestCase):
    def setUp(self) -> None:
        reset_call_ids()

    def test_declined_confirmation_blocks_the_mutation(self):
        calls: list[tuple[str, dict]] = []

        def deny(name, args):
            calls.append((name, args))
            return False

        model = FakeModel([tool_call("refund", {"order_id": "4471"}), "I did not refund it."])
        reg = registry(refund, confirm=deny)
        run = Agent(model, reg).run("refund order 4471")

        self.assertEqual(calls, [("refund", {"order_id": "4471"})])
        self.assertIn("declined", run.steps[0].tool_results[0].content)

    def test_granted_confirmation_allows_the_mutation(self):
        model = FakeModel([tool_call("refund", {"order_id": "4471"}), "Refunded."])
        reg = registry(refund, confirm=lambda n, a: True)
        run = Agent(model, reg).run("refund order 4471")
        self.assertTrue(run.steps[0].tool_results[0].ok)
        self.assertIn("refunded 4471", run.steps[0].tool_results[0].content)

    def test_missing_confirm_handler_crashes_rather_than_degrading(self):
        # A misconfigured registry is a bug, not a run outcome. It must NOT be
        # swallowed into Stop.TOOL_FATAL, or a mutating tool that can never fire
        # looks like an ordinary failed run.
        model = FakeModel([tool_call("refund", {"order_id": "4471"})])
        with self.assertRaises(ToolConfigError):
            Agent(model, registry(refund)).run("refund it")

    def test_runtime_denial_is_a_named_stop_not_a_crash(self):
        # The other half of the distinction: an authorization denial at runtime
        # ends the run cleanly with a stop reason the caller can inspect.
        model = FakeModel([tool_call("forbidden", {})])
        run = Agent(model, registry(forbidden)).run("go")
        self.assertIs(run.stop, Stop.TOOL_FATAL)


class TestTracing(unittest.TestCase):
    def setUp(self) -> None:
        reset_call_ids()

    def test_trace_captures_nested_model_and_tool_spans(self):
        tracer = Tracer()
        model = FakeModel([tool_call("get_order", {"order_id": "4471"}), "Delivered."])
        Agent(model, registry(get_order), tracer=tracer).run("where is 4471")

        self.assertEqual(len(tracer.of_kind("run")), 1)
        self.assertEqual(len(tracer.of_kind("model")), 2)
        self.assertEqual(len(tracer.of_kind("tool")), 1)

        # Tool spans hang off the run, and the run has no parent.
        run_span = tracer.of_kind("run")[0]
        self.assertIsNone(run_span.parent_id)
        for s in tracer.of_kind("tool") + tracer.of_kind("model"):
            self.assertEqual(s.parent_id, run_span.span_id)

    def test_trace_accounts_tokens_and_cost(self):
        tracer = Tracer()
        model = FakeModel([tool_call("search_help", {"q": "refunds"}), "Answer."])
        budget = Budget(price_per_1k_input=1.0, price_per_1k_output=2.0)
        run = Agent(model, registry(search_help), budget=budget, tracer=tracer).run("go")

        self.assertGreater(run.input_tokens, 0)
        self.assertGreater(run.cost, 0)
        self.assertEqual(tracer.total_input_tokens, run.input_tokens)
        self.assertAlmostEqual(tracer.total_cost, run.cost, places=9)

    def test_export_redacts_sensitive_keys(self):
        tracer = Tracer()
        with tracer.span("x", "tool", api_key="sk-live-should-not-appear", q="fine"):
            pass
        exported = tracer.export()
        self.assertNotIn("sk-live", exported)
        self.assertIn("[redacted]", exported)
        self.assertIn("fine", exported)

    def test_tree_renders_the_run(self):
        tracer = Tracer()
        model = FakeModel([tool_call("get_order", {"order_id": "4471"}), "Delivered."])
        Agent(model, registry(get_order), tracer=tracer).run("go")
        tree = tracer.tree()
        self.assertIn("run:agent.run", tree)
        self.assertIn("tool.get_order", tree)


class TestFakeModelItself(unittest.TestCase):
    """The test harness needs to be trustworthy too."""

    def test_running_out_of_replies_is_a_loud_failure(self):
        model = FakeModel(["only one"])
        agent = Agent(model, registry(search_help))
        agent.run("first")
        with self.assertRaises(AssertionError) as ctx:
            agent.run("second")
        self.assertIn("ran out of scripted replies", str(ctx.exception))

    def test_callable_replies_can_inspect_the_conversation(self):
        def reply(msgs):
            saw_tool = any(m.role == "tool" for m in msgs)
            return "Found it." if saw_tool else tool_call("search_help", {"q": "cats"})

        model = FakeModel([reply, reply])
        run = Agent(model, registry(search_help)).run("find cats")
        self.assertTrue(run.ok)
        self.assertEqual(run.output, "Found it.")
        self.assertEqual(run.trajectory(), ["search_help"])

    def test_records_the_tool_schemas_it_was_offered(self):
        model = FakeModel(["ok"])
        Agent(model, registry(get_order, search_help)).run("hi")
        offered = {t["function"]["name"] for t in model.calls[0]["tools"]}
        self.assertEqual(offered, {"get_order", "search_help"})


if __name__ == "__main__":
    unittest.main()