"""
Pradhya · The Capable Series · Day 03 · Exercise
================================================

The minimal tool-use loop. Two tools, one model, the whole shape of an
agent in under 80 lines.

Run (from inside the agents/ folder):
    python tool_use_demo.py
    python tool_use_demo.py "What time is it? Then read ./demo.txt."
"""

from __future__ import annotations

import datetime as dt
import json
import os
import pathlib
import sys

from anthropic import Anthropic

MODEL = "claude-sonnet-4-6"
client = Anthropic()

# --- 1. Declare the tools the model is allowed to call --------------------

TOOLS = [
    {
        "name": "get_current_time",
        "description": (
            "Return the current local date and time. Use when the user "
            "asks about today, now, the time, or the date."
        ),
        "input_schema": {"type": "object", "properties": {}},
    },
    {
        "name": "read_file",
        "description": (
            "Read a UTF-8 text file from disk relative to the current "
            "directory. Use when the user asks you to summarize, "
            "critique, or extract from a file. Returns up to 8000 "
            "characters."
        ),
        "input_schema": {
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"],
        },
    },
]


# --- 2. Implement the tools (these run locally; the model never executes) -

def get_current_time() -> str:
    return dt.datetime.now().isoformat(timespec="seconds")


def read_file(path: str) -> str:
    p = pathlib.Path(path)
    if not p.exists():
        return f"ERROR: file not found at {p}"
    return p.read_text(encoding="utf-8", errors="replace")[:8000]


TOOL_FNS = {
    "get_current_time": lambda **_: get_current_time(),
    "read_file":        lambda **a: read_file(a["path"]),
}


# --- 3. The loop ----------------------------------------------------------

def run(prompt: str) -> None:
    messages: list[dict] = [{"role": "user", "content": prompt}]

    while True:
        resp = client.messages.create(
            model=MODEL,
            max_tokens=1024,
            tools=TOOLS,
            messages=messages,
        )
        messages.append({"role": "assistant", "content": resp.content})

        if resp.stop_reason != "tool_use":
            for block in resp.content:
                if block.type == "text":
                    print(block.text)
            return

        tool_results: list[dict] = []
        for block in resp.content:
            if block.type != "tool_use":
                continue
            name, args = block.name, block.input
            print(f"[tool] {name}({json.dumps(args)})")
            try:
                output = TOOL_FNS[name](**args)
            except Exception as e:
                output = f"ERROR: {e}"
            tool_results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": str(output),
            })
        messages.append({"role": "user", "content": tool_results})


if __name__ == "__main__":
    if not os.environ.get("ANTHROPIC_API_KEY"):
        sys.exit("ANTHROPIC_API_KEY is not set. Get one at console.anthropic.com.")
    default_prompt = (
        "What time is it? Then read ./demo.txt and summarize the "
        "file in three bullets."
    )
    prompt = " ".join(sys.argv[1:]).strip() or default_prompt
    run(prompt)
