"""Baseline: no framework. The Anthropic Python SDK and a hand-written tool loop."""

import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared"))
from support import MODEL, SYSTEM_PROMPT, USER_PROMPT, get_order_status, refund_order  # noqa: E402

import anthropic  # noqa: E402

TOOLS = [
    {
        "name": "get_order_status",
        "description": get_order_status.__doc__,
        "input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}},
                         "required": ["order_id"], "additionalProperties": False},
    },
    {
        "name": "refund_order",
        "description": refund_order.__doc__,
        "input_schema": {"type": "object",
                         "properties": {"order_id": {"type": "string"}, "reason": {"type": "string"}},
                         "required": ["order_id", "reason"], "additionalProperties": False},
    },
]
HANDLERS = {"get_order_status": get_order_status, "refund_order": refund_order}


def run(client, prompt: str = USER_PROMPT, max_steps: int = 8) -> str:
    messages = [{"role": "user", "content": prompt}]
    for _ in range(max_steps):
        response = client.messages.create(
            model=MODEL, max_tokens=16000, system=SYSTEM_PROMPT, tools=TOOLS, messages=messages
        )
        messages.append({"role": "assistant", "content": response.content})
        calls = [b for b in response.content if b.type == "tool_use"]
        if not calls or response.stop_reason in ("refusal", "max_tokens"):
            return "".join(b.text for b in response.content if b.type == "text")
        results = []
        for call in calls:
            try:
                output, is_error = HANDLERS[call.name](**call.input), False
            except Exception as e:  # report tool failures to the model instead of crashing
                output, is_error = f"error: {e}", True
            results.append({"type": "tool_result", "tool_use_id": call.id, "content": output, "is_error": is_error})
        messages.append({"role": "user", "content": results})
    return "[stopped: too many steps]"


if __name__ == "__main__":
    print(run(anthropic.Anthropic()))
