import anthropic
import json
from tools import registry

client = anthropic.Anthropic()

# Anthropic uses 'tools' with slightly different field names
# The structure is: name, description, input_schema
# (OpenAI uses 'parameters'; Anthropic uses 'input_schema')

ANTHROPIC_TOOLS = [
    {
        "name": "search_knowledge_base",
        "description": "Search the company knowledge base for HR, IT, and
finance policies. Use when users ask about internal company documentation.",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Natural language search query"
                }
            },
            "required": ["query"]
        }
    },
    {
        "name": "get_current_date",
        "description": "Get today's date. Use for date-related questions.",
        "input_schema": {
            "type": "object",
            "properties": {},
            "required": []
        }
    }
]


def run_agent_anthropic(task: str, max_steps: int = 10) -> str:
    messages = [{"role": "user", "content": task}]

    for step in range(max_steps):
        response = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=1024,
            tools=ANTHROPIC_TOOLS,
            messages=messages,
        )

        # Check the stop reason
        if response.stop_reason == "end_turn":
            # Final answer — extract text from content blocks
            for block in response.content:
                if block.type == "text":
                    return block.text

        elif response.stop_reason == "tool_use":
            # Model wants to use a tool
            # Add the model’s response to the conversation
            messages.append({
                "role":    "assistant",
                "content": response.content
            })

            # Process each tool call in the response
            tool_results = []
            for block in response.content:
                if block.type == "tool_use":
                    tool_name = block.name
                    tool_args = block.input
                    tool_id   = block.id

                    print(f"Action: {tool_name}({tool_args})")

                    result = registry.execute(tool_name, tool_args)
                    print(f"Observation: {result}")

                    tool_results.append({
                        "type":        "tool_result",
                        "tool_use_id": tool_id,
                        "content":     result
                    })

            # Add all tool results as a single user message
            messages.append({
                "role":    "user",
                "content": tool_results
            })

    return "Max steps reached."
