#!/usr/bin/env python3
"""A minimal agent: a model, one tool (a shell command) and a loop.

Lecture 4, demonstration 1. The agent repairs materials/agent-demo/odd_sums.py
in a temporary copy of that folder. Every command is shown before it runs:
press Enter to run it, or type n to stop the agent. After the loop, the
harness checks the result itself instead of trusting the agent's last words.

    pip install anthropic
    echo 'ANTHROPIC_API_KEY=sk-ant-...' > .env    # once; git ignores .env
    python3 agent.py                              # --yes runs commands without asking

Run it from this folder (materials) or from any other: the key is read from
the file .env next to this script, or else from the shell. The agent's own
commands do not see the key.

The text protocol (one bash-action block per reply, "exit" to finish) follows
https://minimal-agent.com/; a tool-calling API would replace parse_action.
"""

import argparse
import hashlib
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

MODEL = "claude-opus-5-5"
HERE = Path(__file__).resolve().parent
TASK_DIR = HERE / "agent-demo"
ENV_FILE = HERE / ".env"
TASK = ("Fix odd_sums.py so that the tests pass. Do not change test_odd_sums.py or run_tests.py. "
        "Run the tests with: python3 run_tests.py")
SYSTEM = """You are an agent working in a Unix shell, in the folder of a small Python project.
Each reply: one or two sentences about what you will do next, then exactly one command:

```bash-action
<one shell command>
```

You will then see the command's output. Use small steps: look, run the tests, edit, test again.
To edit a file, rewrite it with a heredoc (cat > file <<'EOF' ... EOF) or use sed.
When the task is done and you have seen the tests pass, reply with the command: exit"""


def api_key():
    """ANTHROPIC_API_KEY from the .env file next to this script, else from the shell."""
    if ENV_FILE.exists():
        for line in ENV_FILE.read_text(encoding="utf-8-sig").splitlines():
            name, sep, value = line.strip().removeprefix("export ").partition("=")
            if sep and name.strip() == "ANTHROPIC_API_KEY" and value.strip():
                return value.strip().strip("'\"")
    if os.environ.get("ANTHROPIC_API_KEY"):
        return os.environ["ANTHROPIC_API_KEY"]
    sys.exit(f"No API key. Put the line ANTHROPIC_API_KEY=sk-ant-... into {ENV_FILE}")


def query_lm(client, messages, effort):
    """One request to the model; returns its reply text and the response."""
    response = client.beta.messages.create(
        model=MODEL,
        max_tokens=16000,
        system=SYSTEM,
        messages=messages,
        output_config={"effort": effort},
        betas=["server-side-fallback-2026-07-01"],
        fallbacks="default",  # if a safety classifier declines, retry on another model
    )
    if response.stop_reason == "refusal":
        raise SystemExit(f"The model declined: {response.stop_details}")
    text = "".join(block.text for block in response.content if block.type == "text")
    return text, response


def parse_action(reply):
    blocks = re.findall(r"```bash-action\n(.*?)\n```", reply, flags=re.DOTALL)
    if len(blocks) != 1:
        return None
    return blocks[0].strip()


# The agent's commands get the environment of this program, minus the API key.
AGENT_ENV = {name: value for name, value in os.environ.items() if name != "ANTHROPIC_API_KEY"}


def execute_action(command, cwd):
    try:
        run = subprocess.run(command, shell=True, cwd=cwd, env=AGENT_ENV, capture_output=True, text=True, timeout=30)
    except subprocess.TimeoutExpired:
        return "Timed out after 30 s."
    output = (run.stdout + run.stderr).strip() or "(no output)"
    return f"{output[:4000]}\n[exit code {run.returncode}]"


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--yes", action="store_true", help="run every command without asking")
    parser.add_argument("--max-steps", type=int, default=15)
    parser.add_argument("--effort", default="low", choices=["low", "medium", "high", "xhigh", "max"])
    args = parser.parse_args()

    try:
        import anthropic  # imported here so that --help works without the SDK
    except ImportError:
        sys.exit("The Anthropic SDK is missing: pip install anthropic")
    client = anthropic.Anthropic(api_key=api_key())

    work = Path(tempfile.mkdtemp(prefix="agent-demo-"))
    shutil.copytree(TASK_DIR, work, dirs_exist_ok=True)
    protected = {name: digest(work / name) for name in ("test_odd_sums.py", "run_tests.py")}
    print(f"Working copy: {work}\nTask: {TASK}\n")

    messages = [{"role": "user", "content": TASK}]
    tokens_in = tokens_out = 0
    for step in range(1, args.max_steps + 1):
        reply, response = query_lm(client, messages, args.effort)
        # Append the whole content (thinking blocks included), not only the text.
        messages.append({"role": "assistant", "content": response.content})
        usage = response.usage
        context = usage.input_tokens + (usage.cache_read_input_tokens or 0) + (usage.cache_creation_input_tokens or 0)
        tokens_in += context
        tokens_out += usage.output_tokens
        print(f"── step {step} · context {context} tokens · reply {usage.output_tokens} tokens")
        print(reply.strip())

        command = parse_action(reply)
        if command is None:
            observation = "Format error: reply with exactly one ```bash-action``` block."
        elif command == "exit":
            print("\nThe agent says it is done.")
            break
        else:
            if not args.yes and input("\nRun it? [Enter = yes, n = stop] ").strip().lower() == "n":
                print("Stopped by the person.")
                break
            observation = execute_action(command, work)
        print(f"\n{observation}\n")
        messages.append({"role": "user", "content": observation})
    else:
        print(f"\nStopped: the budget of {args.max_steps} steps is used up.")

    print(f"\nModel calls: {step} · tokens read {tokens_in} · tokens written {tokens_out}")
    print("\nThe harness checks the result itself:")
    for name, before in protected.items():
        print(f"  {name}: {'unchanged' if digest(work / name) == before else 'CHANGED'}")
    tests = subprocess.run([sys.executable, "run_tests.py"], cwd=work, capture_output=True, text=True)
    print("  " + tests.stdout.strip().replace("\n", "\n  "))
    diff = subprocess.run(["diff", "-u", str(TASK_DIR / "odd_sums.py"), str(work / "odd_sums.py")],
                          capture_output=True, text=True).stdout
    print("\n" + (diff or "odd_sums.py is unchanged."))


if __name__ == "__main__":
    main()
